#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <asm/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <linux/if.h>
#include <linux/wireless.h>
#include <ctype.h>
#include <errno.h>
#include "linux/autoconf.h"
#include "config/autoconf.h" //user config
#include "user/busybox/include/autoconf.h" //busybox config
#include "nvram.h"
#include "utils.h"
#include "webs.h"
#include "internet.h"
//#include "wireless.h"
#include "management.h"
//#include "wps.h"
#include "md5.h"
#include "websda.h"
#include "dwdoor.h"

//#define GET_ARRAY_LEN(array,len) {len = (sizeof(array) / sizeof(array[0]) - 1 );} 

//int ncols = 0,nrows = 0;
void websJson(webs_t wp);
void websText(webs_t wp);

static int dwreadwriteDB(unsigned char* sqlstr,unsigned char** zresult,int* ncols,int* nrows);	
static void openclosegate(webs_t wp,unsigned char gatenumber);
static void openclosegate4jsop(webs_t wp,unsigned char gatenumber);
static int getgateName(int eid, webs_t wp, int argc, char_t **argv);
static int getDepartmentName(int eid, webs_t wp, int argc, char_t **argv);
static void dwGateSetting(webs_t wp, char_t *path, char_t *query);
static void dwwritestaff(webs_t wp, char_t *path, char_t *query);
static void chkstaffnum(webs_t wp, char_t *path, char_t *query);

//static int dwreadstaff(int eid, webs_t wp, int argc, char_t **argv);
static void dwreadstaff(webs_t wp, char_t *path, char_t *query);
static void dwDelstaff(webs_t wp, char_t *path, char_t *query);
static void opendoor(webs_t wp, char_t *path, char_t *query);
static void opendoor1(webs_t wp, char_t *path, char_t *query);
static void opendoor2(webs_t wp, char_t *path, char_t *query);
static void opendoor3(webs_t wp, char_t *path, char_t *query);
static void opendoor4(webs_t wp, char_t *path, char_t *query);
static void opendoor4jsonp(webs_t wp, char_t *path, char_t *query);
static int getstaffnum(int eid, webs_t wp, int argc, char_t **argv);
static int getcardnum(int eid, webs_t wp, int argc, char_t **argv);
static void dwumDb(webs_t wp, char_t *path, char_t *query);
static void signatureCheck(webs_t wp, char_t *path, char_t *query);
static void dwsetpage(webs_t wp, char_t *path, char_t *query);
static void setAttendance(webs_t wp, char_t *path, char_t *query);
static int getExtenoflate(int eid, webs_t wp, int argc, char_t **argv);
static int getExtenofearly(int eid, webs_t wp, int argc, char_t **argv);
static int getTolerateoflate(int eid, webs_t wp, int argc, char_t **argv);
static int getTolerateofearly(int eid, webs_t wp, int argc, char_t **argv);
static int getOvertimeafter(int eid, webs_t wp, int argc, char_t **argv);
static int getWorkstart(int eid, webs_t wp, int argc, char_t **argv);
static int getWorkoff(int eid, webs_t wp, int argc, char_t **argv);
static int getmorningWorkoff(int eid, webs_t wp, int argc, char_t **argv);
static int getafternoonWorkstart(int eid, webs_t wp, int argc, char_t **argv);
static int dwreadholiday(int eid, webs_t wp, int argc, char_t **argv);
static void dwDelholiday(webs_t wp, char_t *path, char_t *query);
static void dwwriteholiday(webs_t wp, char_t *path, char_t *query);
static int getsaturdayRest(int eid, webs_t wp, int argc, char_t **argv);
static int getsaturdayAmwork(int eid, webs_t wp, int argc, char_t **argv);
static int getsaturdayPmwork(int eid, webs_t wp, int argc, char_t **argv);
static int getsaturdayAllwork(int eid, webs_t wp, int argc, char_t **argv);
static int getsundayRest(int eid, webs_t wp, int argc, char_t **argv);
static int getsundayAmwork(int eid, webs_t wp, int argc, char_t **argv);
static int getsundayPmwork(int eid, webs_t wp, int argc, char_t **argv);
static int getsundayAllwork(int eid, webs_t wp, int argc, char_t **argv);
static int dwreadoff(int eid, webs_t wp, int argc, char_t **argv);
static int getDpSelection(int eid, webs_t wp, int argc, char_t **argv);
static void dwreadStaffoff(webs_t wp, char_t *path, char_t *query);
static void dwwriteoff(webs_t wp, char_t *path, char_t *query);
static void dwDeloff(webs_t wp, char_t *path, char_t *query);
static void dwreadstatistics(webs_t wp, char_t *path, char_t *query);
static void dwsetformpage(webs_t wp, char_t *path, char_t *query);
//static int dwreadaccess(int eid, webs_t wp, int argc, char_t **argv);
static void dwreadaccess(webs_t wp, char_t *path, char_t *query);
static void dwsetaccesspage(webs_t wp, char_t *path, char_t *query);
static void dwsett2off(webs_t wp, char_t *path, char_t *query);
static int dwGateGet(int eid, webs_t wp, int argc, char_t **argv);
static void dwviewextentaff(webs_t wp, char_t *path, char_t *query);
static void dwDelextenstaff(webs_t wp, char_t *path, char_t *query);
static void signatureChange(webs_t wp, char_t *path, char_t *query);
static int dwreadforce(int eid, webs_t wp, int argc, char_t **argv);
static void dwDelforce(webs_t wp, char_t *path, char_t *query);
static void dwwriteforce(webs_t wp, char_t *path, char_t *query);
static void signatureSet(webs_t wp, char_t *path, char_t *query);
static int getswipecardnum(int eid, webs_t wp, int argc, char_t **argv);
static int getabsentofworkasearly(int eid, webs_t wp, int argc, char_t **argv);
static int getabsentofworkaslate(int eid, webs_t wp, int argc, char_t **argv);
//static void setLans1ite(webs_t wp, char_t *path, char_t *query);
static void setSnum(webs_t wp, char_t *path, char_t *query);
static int getSnum(int eid, webs_t wp, int argc, char_t **argv);
static int getWebADDR(int eid, webs_t wp, int argc, char_t **argv);
static int getgate0CameraADDR(int eid, webs_t wp, int argc, char_t **argv);
static int getgate0CameraPORT(int eid, webs_t wp, int argc, char_t **argv);
static int getgate1CameraADDR(int eid, webs_t wp, int argc, char_t **argv);
static int getgate1CameraPORT(int eid, webs_t wp, int argc, char_t **argv);
static int getreQuesttm(int eid, webs_t wp, int argc, char_t **argv);
static int getVersion(int eid, webs_t wp, int argc, char_t **argv);
static int getWebPORT(int eid, webs_t wp, int argc, char_t **argv);
static int getTcpPORT(int eid, webs_t wp, int argc, char_t **argv);
static void staffinit(webs_t wp, char_t *path, char_t *query);
static int getDetectDevice(int eid, webs_t wp, int argc, char_t **argv);
static int getcmdresult(int eid, webs_t wp, int argc, char_t **argv);
static int getrealtime(int eid, webs_t wp, int argc, char_t **argv);
static int getjqfs(int eid, webs_t wp, int argc, char_t **argv);

void formDefineDwdoor(void)
{
    websFormDefine(T("dwwritestaff"), dwwritestaff);
//	websAspDefine(T("dwreadstaff"), dwreadstaff);
	websFormDefine(T("dwreadstaff"), dwreadstaff);
	websFormDefine(T("chkstaffnum"), chkstaffnum);
	websFormDefine(T("dwsetpage"), dwsetpage);
	websFormDefine(T("dwDelstaff"), dwDelstaff);
//	websFormDefine(T("dwupdatestaff"), dwupdatestaff);
	websFormDefine(T("dwGateSetting"), dwGateSetting);
	websFormDefine(T("opendoor"), opendoor);
	websFormDefine(T("opendoor1"), opendoor1);
	websFormDefine(T("opendoor2"), opendoor2);
	websFormDefine(T("opendoor3"), opendoor3);
	websFormDefine(T("opendoor4"), opendoor4);
	websFormDefine(T("opendoor4jsonp"), opendoor4jsonp);
    websAspDefine(T("getgateName"), getgateName);
	websAspDefine(T("getDepartmentName"), getDepartmentName);
	websAspDefine(T("getstaffnum"), getstaffnum);
	websAspDefine(T("getcardnum"), getcardnum);
	websFormDefine(T("dwumDb"), dwumDb);
	websFormDefine(T("signatureCheck"), signatureCheck);
	websFormDefine(T("setAttendance"), setAttendance);
	websAspDefine(T("getExtenoflate"), getExtenoflate);
	websAspDefine(T("getExtenofearly"), getExtenofearly);
	websAspDefine(T("getTolerateoflate"), getTolerateoflate);
	websAspDefine(T("getTolerateofearly"), getTolerateofearly);
	websAspDefine(T("getOvertimeafter"), getOvertimeafter);
	websAspDefine(T("getWorkstart"), getWorkstart);
	websAspDefine(T("getWorkoff"), getWorkoff);
	websAspDefine(T("getmorningWorkoff"), getmorningWorkoff);
	websAspDefine(T("getafternoonWorkstart"), getafternoonWorkstart);
	websAspDefine(T("dwreadholiday"), dwreadholiday);
	websFormDefine(T("dwDelholiday"), dwDelholiday);
	websFormDefine(T("dwwriteholiday"), dwwriteholiday);
	websAspDefine(T("getsaturdayRest"), getsaturdayRest);
	websAspDefine(T("getsaturdayAmwork"), getsaturdayAmwork);
	websAspDefine(T("getsaturdayPmwork"), getsaturdayPmwork);
	websAspDefine(T("getsaturdayAllwork"), getsaturdayAllwork);
	websAspDefine(T("getsundayRest"), getsundayRest);
	websAspDefine(T("getsundayAmwork"), getsundayAmwork);
	websAspDefine(T("getsundayPmwork"), getsundayPmwork);
	websAspDefine(T("getsundayAllwork"), getsundayAllwork);
	websAspDefine(T("dwreadoff"), dwreadoff);
	websAspDefine(T("getDpSelection"), getDpSelection);
	websFormDefine(T("dwreadStaffoff"), dwreadStaffoff);
	websFormDefine(T("dwwriteoff"), dwwriteoff);
	websFormDefine(T("dwreadstatistics"), dwreadstatistics);
	websFormDefine(T("dwreadaccess"), dwreadaccess);
	websFormDefine(T("dwDeloff"), dwDeloff);
	websFormDefine(T("dwsetformpage"), dwsetformpage);
	websFormDefine(T("dwsetaccesspage"), dwsetaccesspage);
	websFormDefine(T("dwsett2off"), dwsett2off);
	websAspDefine(T("dwGateGet"), dwGateGet);
	websFormDefine(T("dwviewextentaff"), dwviewextentaff);
	websFormDefine(T("dwDelextenstaff"), dwDelextenstaff);
	websFormDefine(T("signatureChange"), signatureChange);
	websAspDefine(T("dwreadforce"), dwreadforce);
	websFormDefine(T("dwDelforce"), dwDelforce);
	websFormDefine(T("dwwriteforce"), dwwriteforce);
	websFormDefine(T("signatureSet"), signatureSet);
	websAspDefine(T("getswipecardnum"), getswipecardnum);
	websAspDefine(T("getabsentofworkasearly"), getabsentofworkasearly);
	websAspDefine(T("getabsentofworkaslate"), getabsentofworkaslate);
	websFormDefine(T("setSnum"), setSnum);
	websAspDefine(T("getSnum"), getSnum);
	websAspDefine(T("getWebADDR"), getWebADDR);
	websAspDefine(T("getgate0CameraADDR"), getgate0CameraADDR);
	websAspDefine(T("getgate0CameraPORT"), getgate0CameraPORT);
	websAspDefine(T("getgate1CameraADDR"), getgate1CameraADDR);
	websAspDefine(T("getgate1CameraPORT"), getgate1CameraPORT);
	websAspDefine(T("getreQuesttm"), getreQuesttm);
	websAspDefine(T("getVersion"), getVersion);
	websAspDefine(T("getWebPORT"), getWebPORT);
	websAspDefine(T("getTcpPORT"), getTcpPORT);
	websFormDefine(T("staffinit"), staffinit);
	websAspDefine(T("getcmdresult"), getcmdresult);
	websAspDefine(T("getrealtime"), getrealtime);
	websAspDefine(T("getjqfs"), getjqfs);
	websAspDefine(T("getDetectDevice"), getDetectDevice);
	
//	websFormDefine(T("setLans1ite"), setLans1ite);
//#ifdef CONFIG_DATE	
//	websFormDefine(T("NTPSyncWithHost"), NTPSyncWithHost);
//#endif
}
/*write OK responsor*/
void websOK(webs_t wp)
{
    a_assert(websValid(wp));
	websWrite(wp, T("HTTP/1.0 200 OK\n")); 
    websWrite(wp, T("Server: %s\r\n"), WEBS_NAME);
    websWrite(wp, T("Pragma: no-cache\n"));
	websWrite(wp, T("Cache-control: no-cache\n"));
	websWrite(wp, T("\n"));
    return;
}

/*write jsop header*/
void websJson(webs_t wp)
{
    a_assert(websValid(wp));
	websWrite(wp, T("HTTP/1.0 200 OK\n")); 
    websWrite(wp, T("Server: %s\r\n"), WEBS_NAME);
    websWrite(wp, T("Pragma: no-cache\n"));
	websWrite(wp, T("Cache-control: no-cache\n"));
	websWrite(wp, T("Content-Type: applicaiton/json;charset=utf-8\n"));
	websWrite(wp, T("\n"));
    return;
}

/*write text header*/
void websText(webs_t wp)
{
    a_assert(websValid(wp));
	websWrite(wp, T("HTTP/1.0 200 OK\n")); 
    websWrite(wp, T("Server: %s\r\n"), WEBS_NAME);
    websWrite(wp, T("Pragma: no-cache\n"));
	websWrite(wp, T("Cache-control: no-cache\n"));
	websWrite(wp, T("Content-Type: text/plain;charset=utf-8\n"));
	websWrite(wp, T("\n"));
    return;
}

/* write to and read from /mnt/user/dwdoor.db */
int dwreadwriteDB(unsigned char* sqlstr,unsigned char** zresult,int* ncols,int* nrows)
{
	int rc,i;
	sqlite3 *conn = NULL;	
	rc = sqlite3_open("/mnt/user/dwdoor.db",&conn);
//	printf("%s ncols:%d %p nrows:%d %p %d\n",sqlstr,ncols,&ncols,nrows,&nrows,__LINE__);
	int nr = 0;
//	printf("ncols:%d nrows:%d %d\n",ncols,nrows,__LINE__);
	int nc = 0;
//	printf("ncols:%d nrows:%d %d\n",ncols,nrows,__LINE__);
	if (rc != SQLITE_OK) 
	{
        sqlite3_close(conn);
        printf("dwreadDB_open_err.\n");
		return -1;
    }
//	printf("dwreadDB_open.%d\n",__LINE__);
	sqlite3_busy_timeout(conn, 180*1000);
	sqlite3_stmt* stmt6 = NULL;
//	printf("dwreadDB_timeout.%d\n",__LINE__);
	if(sqlite3_prepare_v2(conn,sqlstr,strlen(sqlstr),&stmt6,NULL) != SQLITE_OK)
	{
		if(stmt6) sqlite3_finalize(stmt6);
		sqlite3_close(conn);
		printf("dwreadDB_prepare_err. %s %d\n",sqlstr,__LINE__);
		return -1;
	}
	rc = sqlite3_step(stmt6);           
	nc = sqlite3_column_count(stmt6);
//	printf("ncols=%d nrows=%d rc =%d zresult:%p zresult+1:%p %d\n",ncols,nrows,rc,zresult,zresult+1,__LINE__);
//	printf("ncols=%d nrows=%d rc =%d zresult:%p %d\n",ncols,nrows,rc,zresult,__LINE__);
	while(rc == SQLITE_ROW)
	{
		for(i=0;i<nc;i++)
		{
			if(!(sqlite3_column_text(stmt6,i))||!(*(sqlite3_column_text(stmt6,i))))
			{
				strcpy(*(zresult+(nr*nc)+i),"\0");
//				*(zresult+(nrows*ncols)+i)="0";
			}else
			{
//				printf("zresult[%d]=%s %d\n",(nrows*ncols)+i,sqlite3_column_text(stmt6,i),__LINE__);
//              		strcpy(*(zresult+(nrows*ncols)+i),sqlite3_column_text(stmt6,i));
				snprintf(*(zresult+(nr*nc)+i),33,"%s",sqlite3_column_text(stmt6,i));
//				printf("zresult[%d]=%s %p %d\n",(nrows*ncols)+i,*(zresult+(nrows*ncols)+i),*(zresult+(nrows*ncols)+i),__LINE__);
			} 					
		}
		rc = sqlite3_step(stmt6);
		nr++;
	}	
//	printf("nc=%d nr=%d zresult:%s %p %d\n",nc,nr,*zresult,*zresult,__LINE__);
	sqlite3_finalize(stmt6);   	
	sqlite3_close(conn);
	*ncols = nc;
	*nrows = nr;
//	printf("ncols=%d nrows=%d zresult:%s %p len:%d %d\n",*ncols,*nrows,zresult,zresult,strlen(*zresult),__LINE__);
//	return strlen(*zresult);
	return 0;
}

int sncols=0,snrows=0;
/* write to and read from /mnt/user/dwdoor.db for dwreadstatistics*/
static int dwrdwtDBstac(unsigned char* sqlstr,unsigned char** zresult,sqlite3* conn)
{
	int rc,i;
//	sqlite3 *conn = NULL;	
	snrows = 0;
	    sqlite3_stmt* stmt6 = NULL;
        if(sqlite3_prepare_v2(conn,sqlstr,strlen(sqlstr),&stmt6,NULL) != SQLITE_OK)
	    {
            if(stmt6) sqlite3_finalize(stmt6);
            sqlite3_close(conn);
//		    printf("dwreadDB2_prepare_err.\n");
			return -1;
        }else
	    {
            rc = sqlite3_step(stmt6);           
			sncols = sqlite3_column_count(stmt6);
//			printf("sncols=%d snrows=%d rc =%d \n",sncols,snrows,rc);
			while(rc == SQLITE_ROW)
            {
  	     	    for(i=0;i<sncols;i++)
			    {
					if(!(sqlite3_column_text(stmt6,i))||!(*(sqlite3_column_text(stmt6,i))))
					{
                        strcpy(*(zresult+(snrows*sncols)+i),"\0");
					}else
					{
//					    printf("zresult[%d]=%s %d\n",i,sqlite3_column_text(stmt6,i),(nrows*ncols)+i);
						strcpy(*(zresult+(snrows*sncols)+i),sqlite3_column_text(stmt6,i));                         						
                    } 					
			    }
				rc = sqlite3_step(stmt6);
				snrows++;
			}	
		}
	sqlite3_finalize(stmt6);
	return 0;
}

static int getDepartmentName(int eid, webs_t wp, int argc, char_t **argv)
{
//    static unsigned char DepartmentName = 0;
	char_t* DepartmentName = "hr";
	int tmp = 0;
	tmp = websWrite(wp, T("%s"),DepartmentName);
//	websFooter(wp);
//	websDone(wp, 200);
	return tmp; 
}

static int getstaffnum(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	char_t* zStaffnum[1];
	zStaffnum[0] = balloc(B_L,33);
	if(!zStaffnum) perror("zStaffnum");
    strcpy(sqlstr,"select staffnum from staffbasesetting where rowid = (select max(rowid) from staffbasesetting);");
	int ncols=0,nrows=0;	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&zStaffnum,&ncols,&nrows)<0) printf("getstaffnum Db err.\n");
//	printf("zStaffnum=%s\n",*zStaffnum);
	int rc = websWrite(wp, T("%s"),*zStaffnum);
	bfree(B_L,zStaffnum[0]);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getcardnum(int eid, webs_t wp, int argc, char_t **argv)
{
//    int type;
//	char_t *field;
	char* cardnum[1];
	cardnum[0] = balloc(B_L,33);
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
//	if (ejArgs(argc, argv, T("%d %s"), &type, &field) < 2) return websWrite(wp, T("Insufficient args<br/>"));
    strcpy(cardnum[0],"\0");
    snprintf(sqlstr,256,"select cardnum from accessrecord where rowid = (select max(rowid) from accessrecord);"); 
//    printf("sqlstr:%s\n",sqlstr);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&cardnum,&ncols,&nrows)<0) printf("getcardnum Db err.\n");
//    int rc = websWrite(wp, T("%s"), *cardnum);
	int rc = websWrite(wp, T("%s"), cardnum[0]);
	bfree(B_L,cardnum[0]);
	bfree(B_L,sqlstr);
	return rc; 
}

static void dwwritestaff(webs_t wp, char_t *path, char_t *query)
{
	if(!query || (!strlen(query)))
	{	    
		websText(wp);
		websWrite(wp, T("%s<br/>"),"INPUT NULL.");
		websDone(wp, 200);
		return;
	}
	char_t* sqlstr;
	sqlstr = balloc(B_L,512);
	int ncols=0,nrows=0;
	char_t* staffnum = "0";
	char_t* staffname = "0";
	char_t* cardnum = "0";
	char_t* departmentname = "hr";
	char_t* departmentID = "0";
	char_t* gateName = "1";
	char_t* periodofvalitystart = "0";
	char_t* periodofvalityend = "0";
	char_t* staffgender;
	char_t* staffage;
	char_t* picfilename;
	char_t* entrancevalitystart;
	char_t* entrancevalityend;
	char_t* leavevalitystart;
	char_t* leavevalityend;
	char_t* limitenrancenum;
	char_t* limitleavenum;
	int rc = 0,age = 20;
    unsigned char* staffnumbuff[1];
	staffnumbuff[0] = balloc(B_L,33);
	staffnum = websGetVar(wp, T("staffnum"), T("0"));
	staffname = websGetVar(wp, T("staffname"), T("0"));
	cardnum = websGetVar(wp, T("cardnum"), T("0"));
	departmentname = websGetVar(wp, T("departmentname"), T("hr"));
	departmentID = websGetVar(wp, T("departmentID"), T("0"));
	gateName = websGetVar(wp, T("gateName"), T("1"));
	periodofvalitystart = websGetVar(wp, T("periodofvalitystart"), T("0"));
	periodofvalityend = websGetVar(wp, T("periodofvalityend"), T("0"));
	staffgender = websGetVar(wp, T("staffgender"), T("male"));
    staffage = 	websGetVar(wp, T("staffage"), T("20"));
	age=gatoi(staffage);
	picfilename = websGetVar(wp, T("picfilename"), T(""));
	entrancevalitystart = websGetVar(wp, T("entrancevalitystart"), T("00:00:00"));
	entrancevalityend = websGetVar(wp, T("entrancevalityend"), T("23:59:59"));
	leavevalitystart = websGetVar(wp, T("leavevalitystart"), T("00:00:00"));
	leavevalityend = websGetVar(wp, T("leavevalityend"), T("23:59:59"));
	limitenrancenum = websGetVar(wp, T("limitenrancenum"), T("9999"));
	limitleavenum = websGetVar(wp, T("limitleavenum"), T("9999"));
//	printf("departmentID:%s entrancevalitystart:%s entrancevalityend:%s \
	    leavevalitystart:%s leavevalityend:%s staffgender:%s staffage:%s \
		picfilename:%s gateName:%s limitenrancenum:%s limitleavenum:%s %d\n",departmentID,entrancevalitystart,
//		entrancevalityend,leavevalitystart,leavevalityend,staffgender,staffage,
//		picfilename,gateName,limitenrancenum,limitleavenum,__LINE__);
	if(!(*staffnum)||!(*staffname)||!(*cardnum)||!(*departmentname)
	    ||!*(periodofvalitystart)||!*(periodofvalityend)||strlen(staffnum)>32
		||strlen(staffname)>32||strlen(cardnum)>32||strlen(departmentname)>32||!*(entrancevalitystart)
		||!*(entrancevalityend)||!*(leavevalitystart)||!*(leavevalityend)||!(*departmentID)
		||strlen(departmentID)>32)
	{
//	    printf("dwwritestaff_NULL or too long.%d\n",__LINE__);
		websHeader(wp);
        if (!strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))		
	        websWrite(wp, T("<script language=\"JavaScript\">alert('%s');</script><br/>"),"INPUT NULL or too long.");
		if (strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))
		    websWrite(wp, T("<script language=\"JavaScript\">alert('%s');</script><br/>"),"输入为空或太长。");       //don't use '' instead of ""   
		websWrite(wp,T("<script  language=\"JavaScript\">self.setTimeout(window.location.href='/door/staffbasesetting.asp',1000);</script><br/>"));
		websFooter(wp);
	    websDone(wp, 200);
		bfree(B_L,staffnumbuff[0]);
	    bfree(B_L,sqlstr);
		return;
	}else
	{
	    rc = snprintf(sqlstr,511,"select distinct staffnum from staffbasesetting where staffnum='%s';",staffnum);
        rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
		if(strcmp(*staffnumbuff,staffnum)==0)
		{
		    websHeader(wp);	
            if (!strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))			
                websWrite(wp, T("<script language=\"JavaScript\">alert('%s');</script><br/>"),"staffnum is repeat,Please change.");
		    if (strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))			
                websWrite(wp, T("<script language=\"JavaScript\">alert('%s');</script><br/>"),"工号重复,请修改。");   //don't use '' instead of ""
			websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/staffbasesetting.asp',1000);</script><br/>"));
		    websFooter(wp);
	        websDone(wp, 200);
			bfree(B_L,staffnumbuff[0]);
	        bfree(B_L,sqlstr);
			return;
		}
		if(!picfilename||!(*picfilename))
		{
//		    printf("picfilename null.\n");
		}else if(strlen(picfilename)>22)
		{
			websHeader(wp);		
	        if (!strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))	
			    websWrite(wp, ("<script language=\"JavaScript\">alert('%s');</script><br/>"),"Length of picfilename is large than 18,Please change.");
			if (strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))	
			    websWrite(wp, ("<script language=\"JavaScript\">alert('%s');</script><br/>"),"照片文件名太长。");	//don't use '' instead of ""
		    websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/staffbasesetting.asp',1000);</script><br/>"));
			websFooter(wp);
	        websDone(wp, 200);
//			printf("Length of picfilename is large.\n");
			bfree(B_L,staffnumbuff[0]);
	        bfree(B_L,sqlstr);
			return;
		}else
        { 		
		    rc = snprintf(sqlstr,511,"select distinct picfilename from staffbasesetting where picfilename='%s';",picfilename);
            rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
            if(strcmp(*staffnumbuff,picfilename)==0)
		    { 
				websHeader(wp);	
                if (!strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))   				
	                websWrite(wp, ("<script language=\"JavaScript\">alert('%s');</script><br/>"),"picfilename is repeat,Please change.");
				if (!strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))   				
	                websWrite(wp, ("<script language=\"JavaScript\">alert('%s');</script><br/>"),"照片文件名重复。");	//don't use '' instead of ""
		        websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/staffbasesetting.asp',1000);</script><br/>"));
			    websFooter(wp);
	            websDone(wp, 200);
//				printf("picfilename is repeat,Please change.\n");
				bfree(B_L,staffnumbuff[0]);
	            bfree(B_L,sqlstr);
			    return; 
			}
		}
		if(rc!= -1)
		{
		    rc = snprintf(sqlstr,511,"INSERT INTO staffbasesetting(staffnum,staffname,cardnum,departmentname,gatenum,periodofvalitystart,\
	            periodofvalityend,staffgender,staffage,picfilename,departmentID,entrancevalitystart,entrancevalityend,leavevalitystart,\
				leavevalityend,limitenrancenum,limitleavenum) VALUES(\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\");",
				staffnum,staffname,cardnum,departmentname,gateName,periodofvalitystart,periodofvalityend,staffgender,age,picfilename,
				departmentID,entrancevalitystart,entrancevalityend,leavevalitystart,leavevalityend,limitenrancenum,limitleavenum);
//	        printf("sqlstr:%s %d\n",sqlstr,__LINE__);
			websHeader(wp);
		    if(dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows)<0) 
			{
			    websWrite(wp, ("<script language=\"JavaScript\">alert('%s');</script><br/>"),"WRITE DB ERR.");		
            }else
			{
			    if (!strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))   					                
				    websWrite(wp, ("<script language=\"JavaScript\">alert('%s');</script><br/>"),"Input staff info success.");
			    if (strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))   					                
				    websWrite(wp, ("<script language=\"JavaScript\">alert('%s');</script><br/>"),"添加员工信息成功。"); //don't use '' instead of ""
			}
			websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(parent.location.href='/door/staffbasesetting.asp',1000);</script><br/>")); 
	        websFooter(wp);
	        websDone(wp, 200);
		}        		
    }
	bfree(B_L,staffnumbuff[0]);
	bfree(B_L,sqlstr);
	return;
}

static void chkstaffnum(webs_t wp, char_t *path, char_t *query)
{
    if(!query || (!strlen(query)))
	{
	    websText(wp);
		websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
    char_t* staffnum;
	staffnum=balloc(B_L,33);
	strcpy(staffnum,query);
	char_t* sqlstr;
	sqlstr = balloc(B_L,512);
	int ncols=0,nrows=0;
	unsigned char* staffnumbuff[1];
	staffnumbuff[0] = balloc(B_L,33);
	strcpy(staffnumbuff[0],"\0");
	snprintf(sqlstr,511,"select distinct staffnum from staffbasesetting where staffnum='%s';",staffnum);
    websText(wp);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows)<0)
	{
	    websWrite(wp, T("%s<br/>"),"WRITE DB ERR.");
	}
	if(strcmp(*staffnumbuff,staffnum)==0)
	{	
//        websText(wp);
		websWrite(wp, T("repeat"));
//		printf("chkstaffnum repeat. \n");
	}else
	{
//	    websText(wp);
		websWrite(wp, T("notrpt"));
//		printf("chkstaffnum notrpt. \n");
	}
	websDone(wp, 200);
	bfree(B_L,staffnumbuff[0]);
	bfree(B_L,staffnum);
	bfree(B_L,sqlstr);
	return;
}

int pagenum=1;
static void dwsetpage(webs_t wp, char_t *path, char_t *query)
{
	if(!query || (!strlen(query)))
	{
	    websText(wp);
		websWrite(wp, T("%s<br/>"),"query NULL.");
//		printf("query NULL.\n");
//		websWrite(wp, T("%s"),"200");
        websWrite(wp, T("HTTP/1.0 200 OK\n"));
		websDone(wp, 200);
		return;
	}
	if(gatoi(query)>=1) pagenum=gatoi(query);
//	printf("query:%s pagenum:%d\n",query,pagenum);
//	websWrite(wp, T("%s"),"200");
    websWrite(wp, T("HTTP/1.0 200 OK\n"));
	websDone(wp, 200);
}

//static int dwreadstaff(int eid, webs_t wp, int argc, char_t **argv)
static void dwreadstaff(webs_t wp, char_t *path, char_t *query)
{   
//	printf("query %s. %d\n",query,__LINE__);
	if(!query || (!strlen(query)))
	{
	    websText(wp);
		websWrite(wp, T("%s<br/>"),"query NULL.");
		printf("query NULL. %d\n",__LINE__);
//		websWrite(wp, T("%s"),"200");
//        websWrite(wp, T("HTTP/1.0 200 OK\n"));
		websDone(wp, 200);
		return;
	}
	char_t* yeshuchuan[24]={0};
	char_t* sIndex1=strstr(query,"\"yeshu\":\"");
	if(sIndex1)
	{
		snprintf(yeshuchuan,24,"%s",sIndex1+9);
		sIndex1=strchr(yeshuchuan,'"');
		if(sIndex1) *sIndex1='\0';
	}	
	int yeshu=1;
	if(strlen(yeshuchuan)) yeshu = atoi(yeshuchuan);
	int pagestart=1;
	int pageend=1;
	static unsigned char i,j;
    pagestart=10*pagenum-10;
    pageend=10;	
//	printf("yeshu:%d pagenum:%d pagestart:%d pageend:%d %d\n",yeshu,pagenum,pagestart,pageend,__LINE__);
	char_t* rowsnum;
	rowsnum = balloc(B_L,33);
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	strcpy(sqlstr,"select COUNT(*) from staffbasesetting;");
	if(dwreadwriteDB(sqlstr,(unsigned char**)&rowsnum,&ncols,&nrows)<0)
	{
	    printf("dwreadstaff select0 err. %s %d\n",sqlstr,__LINE__);
		websWrite(wp,T("dwreadstaff select0 err."));
		bfree(B_L,rowsnum);
	    bfree(B_L,sqlstr);
		return -1;
	}
	char_t* s;
	s = balloc(B_L,48);		
	char_t* staffbasesettingtab;
	staffbasesettingtab = balloc(B_L,2048);
	strcpy(staffbasesettingtab,"{\0");
	char_t* dbResult[102];
	for(i=0;i<102;i++)
	{
	    dbResult[i] = balloc(B_L,33);	
	}	
//	printf("rowsnum=%s\n",rowsnum);
	int pagemax=1;
	pagemax = (((gatoi(rowsnum))/10.0)-(int)((gatoi(rowsnum))/10.0))>0.?(int)((gatoi(rowsnum))/10.0)+
	    1:(int)((gatoi(rowsnum))/10.0);	
//	printf("pagemax=%d\n",pagemax);
	snprintf(sqlstr,255,"select rowid,staffnum,staffname,cardnum,departmentname,gatenum, periodofvalitystart,periodofvalityend from staffbasesetting ORDER BY rowid DESC limit %d,%d;",pagestart,pageend);
//    printf("sqlstr:%s %d\n",sqlstr,__LINE__);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&dbResult,&ncols,&nrows)<0) printf("dwreadstaff select1 err.\n");
//	printf("nrows=%d,ncols=%d %d\n",nrows,ncols,__LINE__);	
	for(i=1;i<=nrows;i++)
	{
	    for(j=1;j<=ncols;j++)
		{
//			if(i==1&&j==1)
//			{
//			    sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"pagemax\":\"%d\",\"pagenum\":\"%d\",\"s%d_%d\":\"%s\""
//     				,nrows,ncols,pagemax,pagenum,i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
//			    strcat(staffbasesettingtab,s);
//		    }else
//			{
			    snprintf(s,48,"\"s%d_%d\":\"%s\",",i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
			    strcat(staffbasesettingtab,s);
				if(strlen(staffbasesettingtab)>=1953) break;
//			}
		}		
	}
	snprintf(sqlstr,95,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"pagemax\":\"%d\",\"pagenum\":\"%d\"}"
     				,nrows,ncols,pagemax,pagenum);	
	strcat(staffbasesettingtab,sqlstr);
//    printf("staffbasesettingtab:%s length:%d %d\n",staffbasesettingtab,strlen(staffbasesettingtab),__LINE__);	
	websText(wp);
	websWrite(wp, T("%s"),staffbasesettingtab);
	websDone(wp, 200);

	for(i=0;i<102;i++)
	{
	    bfree(B_L,dbResult[i]);
	}
	bfree(B_L,rowsnum);
	bfree(B_L,s);
	bfree(B_L,staffbasesettingtab);
	bfree(B_L,sqlstr);
	return 0;
}

static void dwDelstaff(webs_t wp, char_t *path, char_t *query)
{
    printf("%s %d\n",query,__LINE__);	
//	rtl = balloc(B_L,len);
    int len = strlen(query);
	if(!(*query) || (!len))
	{
	    websText(wp);
		websWrite(wp, T("%s<br/>"),"query NULL.");
	    websDone(wp, 200);
		printf("%s %d\n",query,__LINE__);	
//	    bfree(B_L,rtl);
		return;
	}
	int i=0;
	char_t* str;
	str = balloc(B_L,64);
	char_t* sqlstr;
	sqlstr= balloc(B_L,128);
	int ncols=0,nrows=0;
	char_t* rtl;	
	rtl = balloc(B_L,33);
	unsigned char* gonghaochuan[32]={0};
//	printf("delArr1:%s len:%d strlen(query):%d %d\n",query,len,strlen(query),__LINE__);
//	GET_ARRAY_LEN(query,len);
//	printf("delArr1:%s delArr1[0]:%s len:%d strlen(query):%d %d\n",query,query[0],len,strlen(query),__LINE__);
	char* index = strstr(query,"\"gonghao\":\"");
	if(index)
	{
		snprintf(gonghaochuan,32,"%s",index+11);
		index = strchr(gonghaochuan,'"');
		if(index) *index='\0';
	}
		
//	index = strchr(query,',');
	int flag=0;
/*	while(index)
	{
		*index='\0';		
		snprintf(str,64,"%s",query);*/		
//	for(i=0;i<len;i++)
//	{
//		int index = atoi(query[i]);
//		snprintf(sqlstr,"delete from staffbasesetting where rowid=%d;",index);
//		snprintf(sqlstr,"delete from staffbasesetting where rowid=%s;",query[i]);
		snprintf(sqlstr,128,"delete from staffbasesetting where staffnum=%s and staffnum!='1';",gonghaochuan);
		printf("sqlstr:%s %d\n",sqlstr,__LINE__);
		if(dwreadwriteDB(sqlstr,(unsigned char**)&rtl,&ncols,&nrows)<0) 
		{
	//	    printf("dwreadstaff delete err.%d\n",__LINE__);
//			websText(wp);
//			websWrite(wp, T("%s"),"dwdeletetaff err.");
			flag=-1;
		}else
		{
//			websWrite(wp, T("HTTP/1.0 200 OK\n"));	
	    }
/*		snprintf(query,len,"%s",index+1);
		index = strchr(query,',');
//	}
	}
	if(strlen(query))
	{
		snprintf(sqlstr,128,"delete from staffbasesetting where rowid=%s;",query);
		printf("sqlstr:%s %d\n",sqlstr,__LINE__);
		if(dwreadwriteDB(sqlstr,(unsigned char**)&rtl,&ncols,&nrows)<0) 
		{
	//	    printf("dwreadstaff delete err.%d\n",__LINE__);
//			websText(wp);
//			websWrite(wp, T("%s"),"dwdeletetaff err.");
			flag=-1;
		}else
		{
//			websWrite(wp, T("HTTP/1.0 200 OK\n"));	
		}
	}*/
/*	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&rtl)<0)
	{
//	    printf("dwreadstaff delete err.%d\n",__LINE__);
	    websText(wp);
		websWrite(wp, T("%s"),"dwdeletetaff err.");
	}else
	{*/
//	    websHeader(wp);
//        websWrite(wp, T("%s"),"200");	
//        websWrite(wp, T("HTTP/1.0 200 OK\n"));	
//    }
	websHeader(wp);
	if(flag==0)
	{
		websWrite(wp, T("{\"jieguo\":\"chenggong\"}"));
	}else
	{
		websWrite(wp, T("{\"jieguo\":\"chucuo\"}"));
	}
	websDone(wp, 200);
	bfree(B_L,rtl);
	bfree(B_L,sqlstr);
	bfree(B_L,str);
}

static int getgateName(int eid, webs_t wp, int argc, char_t **argv)
{
   char_t* GateNametab;
   balloc(B_L,96);
   snprintf(GateNametab,95,"{\"nrows\":\"5\",\"s1_0\":\"all\",\"s1_1\":\"gate1\",\"s1_2\":\"gate2\",\"s1_3\":\"gate3\",\"s1_4\":\"gate4\"}");
//   printf("GateNametab:%s\n",GateNametab);
   websWrite(wp, T("GateNametab"));
   bfree(B_L,GateNametab);
   return 0;
}

static int dwGateGet(int eid, webs_t wp, int argc, char_t **argv)
{
    int i,j=0;
	char_t* s;
	s = balloc(B_L,49);	
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
//	int ncols=0,nrows=0;
	char_t* GateGettab;
	GateGettab = balloc(B_L,1024);
	strcpy(GateGettab,"{\0");
	char_t* dbResult[40];
	for(i=0;i<40;i++)
	{
	    dbResult[i] = balloc(B_L,33);
	}
	int nrows=4,ncols=9;
	char_t* rowsnum;
	rowsnum = balloc(B_L,16);
    snprintf(sqlstr,255,"select gatenum,gatename,region,controlmethod,delayopentime,delayclosetime,  sensorstat,antipassback,attendancecheck from gatesetting;");
//    printf("sqlstr:%s\n",sqlstr);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&dbResult,&ncols,&nrows)<0) printf("dwGateGet Db err.\n");
//	printf("nrows=%d,ncols=%d\n",nrows,ncols);	
	for(i=1;i<=nrows;i++)
	{
	    for(j=1;j<=ncols;j++)
		{
//			if(i==1&&j==1)
//			{
//			    sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"s%d_%d\":\"%s\""
//     				,nrows,ncols,i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
//			    strcat(GateGettab,s);
//		    }else
//			{
			    snprintf(s,48,"\"s%d_%d\":\"%s\",",i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
			    strcat(GateGettab,s);
				if(strlen(GateGettab)>=929) break;
//			}
		}		
	}
	snprintf(sqlstr,48,"\"nrows\":\"%d\",\"ncols\":\"%d\"}",nrows,ncols);
	strcat(GateGettab,sqlstr);
//    printf("%s\n",GateGettab);	
	websWrite(wp, T("%s"),GateGettab);
//	websDone(wp, 200); 
	for(i=0;i<40;i++)
	{
	    bfree(B_L,dbResult[i]);
	}
	bfree(B_L,rowsnum);
	bfree(B_L,s);
	bfree(B_L,GateGettab);
	bfree(B_L,sqlstr);
	return 0;
}

static void dwGateSetting(webs_t wp, char_t *path, char_t *query)
{
	char_t* gateNamestr;
	char_t* gateNumstr;
	char_t* region;
	char_t* Controlmethod;
	char_t* delayopentime;
	char_t* delayclosetime;
	char_t* sensorstat;
	char_t* attendancecheck;
	char_t* antipassback;
	gateNumstr = websGetVar(wp, T("gatenum"), T("all"));
	gateNamestr = websGetVar(wp, T("gatename"), T("null"));	
	region =  websGetVar(wp, T("region"), T("null"));	
	Controlmethod = websGetVar(wp, T("controlmethod"), T("card"));
	delayopentime = websGetVar(wp, T("delayopentime"), T("0"));
	delayclosetime = websGetVar(wp, T("delayclosetime"), T("3"));
	sensorstat = websGetVar(wp, T("sensorstat"), T("ok"));
	attendancecheck = websGetVar(wp, T("attendancecheck"), T("yes"));
	antipassback = websGetVar(wp, T("antipassback"), T("yes"));
	char_t* sqlstr;
	sqlstr = balloc(B_L,512);
	if((!gateNumstr)||!(*gateNumstr)||(!gateNamestr)||!(*gateNamestr)||(!region)||!(*region)||(!Controlmethod)||!(*Controlmethod)||(!delayopentime)||!*(delayopentime)||(!delayclosetime)||!*(delayclosetime)||(!sensorstat)||!*(sensorstat)||(!attendancecheck)||!*(attendancecheck)
		||strlen(gateNumstr)>18||strlen(gateNamestr)>18||strlen(region)>18||strlen(Controlmethod)>18)
	{
	    printf("dwGateSetting_NULL_long.\n");
		sprintf(sqlstr,"INPUT NULL or too long.");
		websHeader(wp);		
	    websWrite(wp, T("%s<br/>"),sqlstr);
		websFooter(wp);
	    websDone(wp, 200);
		bfree(B_L,sqlstr);
		return;
	}
    
	int ncols=0,nrows=0;
    int rc;	
    char_t* Gateset;
	Gateset=balloc(B_L,33);
    websHeader(wp);	
	if(!strcmp(gateNumstr,"all")||!strcmp(gateNumstr,"0"))
	{   
	    snprintf(sqlstr,511,"UPDATE gatesetting SET gatename='%s',region='%s',controlmethod='%s',delayopentime='%s',delayclosetime='%s',sensorstat='%s',attendancecheck='%s',antipassback='%s' where gatenum='0';",gateNamestr,region,Controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,antipassback);		
		rc = dwreadwriteDB(sqlstr,(unsigned char**)&Gateset,&ncols,&nrows);
		if(rc<0) 
		{ 
		    printf("%s __LINE__:%d\n",sqlstr,__LINE__);
            websWrite(wp,T("dwGateSetting1 insert err."));
		}	
	}
	if(!strcmp(gateNumstr,"all")||!strcmp(gateNumstr,"1"))                      
    {   
	    snprintf(sqlstr,511,"UPDATE gatesetting SET gatename='%s',region='%s',controlmethod='%s',delayopentime='%s',delayclosetime='%s',sensorstat='%s',attendancecheck='%s',antipassback='%s' where gatenum='1';",gateNamestr,region,Controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,antipassback);
		rc = dwreadwriteDB(sqlstr,(unsigned char**)&Gateset,&ncols,&nrows);
	    if(rc<0)
		{
		    printf("%s __LINE__:%d\n",sqlstr,__LINE__);
	        websWrite(wp,T("dwGateSetting2 insert err."));
		}
	}
	if(!strcmp(gateNumstr,"all")||!strcmp(gateNumstr,"2")) 
    {   
	    snprintf(sqlstr,511,"UPDATE gatesetting SET gatename='%s',region='%s',controlmethod='%s',delayopentime='%s',delayclosetime='%s',sensorstat='%s',attendancecheck='%s',antipassback='%s' where gatenum='2';",gateNamestr,region,Controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,antipassback);
		rc = dwreadwriteDB(sqlstr,(unsigned char**)&Gateset,&ncols,&nrows);
	    if(rc<0)
        {
//     		printf("%s __LINE__:%d\n",sqlstr,__LINE__);	
	        websWrite(wp,T("dwGateSetting3 insert err."));
		}
	}
	if(!strcmp(gateNumstr,"all")||!strcmp(gateNumstr,"3")) 
    {   
	    snprintf(sqlstr,511,"UPDATE gatesetting SET gatename='%s',region='%s',controlmethod='%s',delayopentime='%s',delayclosetime='%s',sensorstat='%s',attendancecheck='%s',antipassback='%s' where gatenum='3';",gateNamestr,region,Controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,antipassback);
	    rc = dwreadwriteDB(sqlstr,(unsigned char**)&Gateset,&ncols,&nrows);
	    if(rc<0)
		{
//    		printf("%s __LINE__:%d\n",sqlstr,__LINE__);
	        websWrite(wp,T("dwGateSetting4 insert err."));
		}
	}				
	websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href=\"/door/gatesetting.asp\",3000);</script><br/>"));
	websFooter(wp);
	websDone(wp, 200);
	bfree(B_L,sqlstr);
	bfree(B_L,Gateset);
	return;
}
//father process handle son process
/*int signm[16]={0},count=0;
void sig_child_handler(int signo)         
{
    pid_t pid;
    int status,i;
//	printf("signo:%d \n",signo);
    for(i=0;i<16;i++)
	{
        if(signm[i]>0)
		{
		    while((pid=waitpid(signm[i],&status,WNOHANG))>0)
			{
 	   			signm[i]=0;
//				printf("dwdoor child %d exit %d\n",pid,__LINE__);
			}
        }
	}
    return;
}*/

void openclosegate(webs_t wp,unsigned char gatenumber)
{    
    unsigned char  delayopentime = 0,delayclosetime = 1;
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* zresult[2];
	zresult[0]=balloc(B_L,33);
	zresult[1]=balloc(B_L,33);
	snprintf(sqlstr,255,"select delayopentime,delayclosetime from gatesetting where gatenum='%d';",gatenumber);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&zresult,&ncols,&nrows)<0) printf("openclosegate Db err.\n");
	delayopentime = gatoi(zresult[0]);
    delayclosetime = gatoi(zresult[1]);
	if(delayclosetime==0) delayclosetime=1;
	bfree(B_L,sqlstr);
	bfree(B_L,zresult[0]);
	bfree(B_L,zresult[1]);
//	printf("delayopentime:%d delayclosetime:%d\n",delayopentime,delayclosetime);	
    static int wgfd = -1;
    my_gpio_value lock_ctl_value[DWWD_GATE_NUMBER+1] = {{GATE1_LOCK_CTL,GATE_CLOSE},{GATE2_LOCK_CTL,GATE_CLOSE},{GATE3_LOCK_CTL,GATE_CLOSE},{GATE4_LOCK_CTL,GATE_CLOSE},{ALARMOUT,GATE_CLOSE}};
	if(gatenumber>4)
	{
//	    printf("gatenumber out of range \n");
		websOK(wp);    //don't delete.
	    websDone(wp, 200);
		return;
//		exit(0);
	}
//	signal(SIGCHLD,sig_child_handler);
	signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
	pid_t fpid=fork();
/*	if(count<16)
	{
	   signm[count]=fpid;
	   count++;
	   if(count==16) count=0;
	}*/
	if(fpid<0) printf("fork err. %d\n",fpid);
	if(fpid==0)
	{
//	    printf("0fpid=%d\n",getpid());
		websOK(wp);    //don't delete.
//		websText(wp);
//		websWrite(wp, T("door%dopen"),gatenumber);
		websDone(wp, 200);
		sleep(delayopentime);
	    lock_ctl_value[gatenumber].vaule = GATE_OPEN;
	    wgfd = open(WG_GPIO_DEV, O_RDONLY);
	    if (wgfd < 0) 
	    {
	        websOK(wp);    //don't delete.
	        websDone(wp, 200);
			perror("WG_GPIO_DEV");
		    exit(0);
	    }else
	    {
	        if (ioctl(wgfd, DWWD_GPIO_SET, &lock_ctl_value[gatenumber]) < 0)
	        {    
	            if(close(wgfd)) 
			    {
//			        printf("ioctl_err1 close gate[%d] \n",gatenumber);
				    websOK(wp);    //don't delete.
	                websDone(wp, 200);
					exit(0);
		        }
//			    printf("gate[%d]_set_err index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
//		    sprintf(content,"gate[%d]_set_err index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
//		    dwwrite(content);
                websOK(wp);    //don't delete.
	            websDone(wp, 200);
                exit(0); 
		    }else
		    {
		        if(close(wgfd))
                {
//    	    	    printf("ioctl_err2 close gate[%d]\n",gatenumber);
				    websOK(wp);    //don't delete.
	                websDone(wp, 200);
         			exit(0);
			    }							    				
//				printf("gate[%d] open index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
			    sleep(delayclosetime);
			    lock_ctl_value[gatenumber].vaule = GATE_CLOSE;            
		        wgfd = open(WG_GPIO_DEV, O_RDONLY);				
			    if (wgfd < 0) 
	            {
		            perror("WG_GPIO_DEV");
					websOK(wp);    //don't delete.
	                websDone(wp, 200);
			        exit(0);
	            }else
				{
			        if (ioctl(wgfd, DWWD_GPIO_SET, &lock_ctl_value[gatenumber]) < 0)
		            {    
		                if(close(wgfd))
				        {
//					        printf("ioctl_err3 close gate[%d]\n",gatenumber);
					        exit(0);
					    }
						websOK(wp);    //don't delete.
	                    websDone(wp, 200);
//				        printf("gate[%d]_set_err index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
//			            sprintf(content,"gate[%d]_set_err index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
//			            dwwrite(content);
                        exit(0);
                    } else                    
					{
			            if(close(wgfd))
                        {
//					        printf("ioctl_err4 close gate[%d] \n",gatenumber);
			                websOK(wp);    //don't delete.
	                        websDone(wp, 200);
							exit(0);
						}
//						printf("gate[%d] close index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
			            exit(0);
					}
				    exit(0);	
		        }
			    exit(0);	
		    }
            exit(0);			
	    }
//		websOK(wp);    //don't delete.
//		websText(wp);
//		websWrite(wp, T("door%dopen"),gatenumber);
//		websDone(wp, 200);
		exit(0);
	}
/*	{
	    pid_t pid;
        int status;
		printf("dwdoor father \n");
        while((pid=waitpid(fpid,&status,WNOHANG))==0)
		{
		    if(pid>0)
            {	
    			printf("dwdoor child %d exit\n",pid);
				break;			    
		    }
		} 
        printf("00_dwdoor child %d exit\n",pid);		
    }  
	printf("1fpid=%d\n",getpid()); */
    return;		
}
static void opendoor(webs_t wp, char_t *path, char_t *query)
{
	if(!query || (!strlen(query)))
	{
//		printf("input null.\n");
		websText(wp);
		websWrite(wp, T("input null.<br/>"));
		websDone(wp, 200);		
		return;
	}
	if(strchr(query, ';'))
	{
    	websText(wp);
		websWrite(wp, T("input err.<br/>"));
		websDone(wp, 200);
		return;
	}
//	printf("query:%s\n",query);
	int rc;
	rc = strcmp(query,"opendoor1");
	if (!rc)
	{
	    openclosegate(wp,0);
	}else
	{
	    rc = strcmp(query,"opendoor2");
	    if (!rc)
        {
	        openclosegate(wp,1);
	    }else
	    {
	        rc = strcmp(query,"opendoor3");
		    if (!rc)
            {
	            openclosegate(wp,2);
	        }else
	        {
	            rc = strcmp(query,"opendoor4");
	            if (!rc)
				{
	                openclosegate(wp,3);
	            }else
	            {
//				    printf("EER:query == %s",query);
		        }
		    }
	    }
	}
}
static void opendoor1(webs_t wp, char_t *path, char_t *query)
{
	int rc;
	rc = strcmp(query,"opendoor1");
	a_assert(websValid(wp));
	if (!rc)
	{
	    openclosegate(wp,0);
	}
}
static void opendoor2(webs_t wp, char_t *path, char_t *query)
{
	int rc;
	rc = strcmp(query,"opendoor2");
	a_assert(websValid(wp));
	if (!rc)
	{
	    openclosegate(wp,1);
	}
}
static void opendoor3(webs_t wp, char_t *path, char_t *query)
{
	int rc;
	rc = strcmp(query,"opendoor3");
	a_assert(websValid(wp));
	if (!rc)
	{
	    openclosegate(wp,2);
	}
}
static void opendoor4(webs_t wp, char_t *path, char_t *query)
{
	int rc;
	rc = strcmp(query,"opendoor4");
	a_assert(websValid(wp));
	if (!rc)
	{
	    openclosegate(wp,3);
	}
}
void openclosegate4jsop(webs_t wp,unsigned char gatenumber)
{    
    unsigned char  delayopentime = 0,delayclosetime = 1;
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* zresult[2];
	zresult[0]=balloc(B_L,33);
	zresult[1]=balloc(B_L,33);
	snprintf(sqlstr,255,"select delayopentime,delayclosetime from gatesetting where gatenum='%d';",gatenumber);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&zresult,&ncols,&nrows)<0) printf("openclosegate Db err.\n");
	delayopentime = gatoi(zresult[0]);
    delayclosetime = gatoi(zresult[1]);
	if(delayclosetime==0) delayclosetime=1;
	bfree(B_L,sqlstr);
	bfree(B_L,zresult[0]);
	bfree(B_L,zresult[1]);
//	printf("delayopentime:%d delayclosetime:%d\n",delayopentime,delayclosetime);
    char_t* authValue;
	authValue = balloc(B_L,40);
//	char_t* b64en;
//	b64en = balloc(B_L,512);
	char_t* auReturn;
	auReturn=balloc(B_L,256);
	char_t* auReturnpre;
	auReturnpre=balloc(B_L,256);
	char_t *nonce;
	nonce = balloc(B_L,48);
	nonce = websCalcNonce(wp);
//	printf("nonce:%s\n",nonce);
	char_t* expirytime;
	expirytime=balloc(B_L,16);
	strcpy(expirytime,"1440");
//	printf("expirytime:%s\n",expirytime);	
    static int wgfd = -1;
    my_gpio_value lock_ctl_value[DWWD_GATE_NUMBER] = {{GATE1_LOCK_CTL,1},\
                                                  {GATE2_LOCK_CTL,1}};
	if(gatenumber>3)
	{
//	    printf("gatenumber out of range \n");
		snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"gatenumber%derr\",\"realm\":\"%s\",\"nonce\":\
			\"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		websEncode64(auReturn,auReturnpre,256);
		websText(wp);
	    websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	    websDone(wp, 200);
		bfree(B_L,authValue);
		bfree(B_L,nonce);
	    bfree(B_L,expirytime);
		bfree(B_L,auReturnpre);
//		bfree(B_L,b64en);
	    bfree(B_L,auReturn);  
		return;
//		exit(0);
	}
//	signal(SIGCHLD,sig_child_handler);
	signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
	pid_t fpid=fork();
/*	if(count<16)
	{
	   signm[count]=fpid;
	   count++;
	   if(count==16) count=0;
	}*/
	if(fpid<0) printf("fork err. %d\n",fpid);
	if(fpid==0)
	{
//	    printf("fpid=%d\n",getpid());
		sleep(delayopentime);
	    lock_ctl_value[gatenumber].vaule = GATE_OPEN;
	    wgfd = open(WG_GPIO_DEV, O_RDONLY);
	    if (wgfd < 0) 
	    {
//	        perror("WG_GPIO_DEV");
			snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door%derr\",\"realm\":\"%s\",\"nonce\":\
			    \"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		    websEncode64(auReturn,auReturnpre,256);
			websText(wp);
	        websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	        websDone(wp, 200);
			bfree(B_L,authValue);
		    bfree(B_L,nonce);
	        bfree(B_L,expirytime);
		    bfree(B_L,auReturnpre);
//			bfree(B_L,b64en);
	        bfree(B_L,auReturn);
		    exit(0);
	    }else
	    {
	        if (ioctl(wgfd, DWWD_GPIO_SET, &lock_ctl_value[gatenumber]) < 0)
	        {    
	            if(close(wgfd)) 
			    {
//			        printf("ioctl_err1 close gate[%d] \n",gatenumber);
					snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door%derr\",\"realm\":\"%s\",\"nonce\":\
			            \"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		            websEncode64(auReturn,auReturnpre,256);
					websText(wp);
	                websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	                websDone(wp, 200);
					bfree(B_L,authValue);
		            bfree(B_L,nonce);
	                bfree(B_L,expirytime);
		            bfree(B_L,auReturnpre);
//					bfree(B_L,b64en);
	                bfree(B_L,auReturn);
				    exit(0);
		        }
//			    printf("gate[%d]_set_err index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
//		    sprintf(content,"gate[%d]_set_err index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
//		    dwwrite(content);
                snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door%derr\",\"realm\":\"%s\",\"nonce\":\
			        \"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		        websEncode64(auReturn,auReturnpre,256);
				websText(wp);
	            websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	            websDone(wp, 200);
				bfree(B_L,authValue);
		        bfree(B_L,nonce);
	            bfree(B_L,expirytime);
		        bfree(B_L,auReturnpre);
//                bfree(B_L,b64en);
	            bfree(B_L,auReturn);				
                exit(0); 
		    }else
		    {
		        if(close(wgfd))
                {
//    	    	    printf("ioctl_err2 close gate[%d]\n",gatenumber);
				    snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door%derr\",\"realm\":\"%s\",\"nonce\":\
			            \"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		            websEncode64(auReturn,auReturnpre,256);
					websText(wp);
	                websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	                websDone(wp, 200);
					bfree(B_L,authValue);
		            bfree(B_L,nonce);
	                bfree(B_L,expirytime);
		            bfree(B_L,auReturnpre);
//					bfree(B_L,b64en);
	                bfree(B_L,auReturn);
					exit(0);
			    }								
//				printf("gate[%d] open index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
			    sleep(delayclosetime);
			    lock_ctl_value[gatenumber].vaule = GATE_CLOSE;            
		        wgfd = open(WG_GPIO_DEV, O_RDONLY);				
			    if (wgfd < 0) 
	            {
		            perror("WG_GPIO_DEV");
					snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door%derr\",\"realm\":\"%s\",\"nonce\":\
			            \"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		            websText(wp);
	                websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	                websDone(wp, 200);
					websEncode64(auReturn,auReturnpre,256);
					bfree(B_L,authValue);
		            bfree(B_L,nonce);
	                bfree(B_L,expirytime);
		            bfree(B_L,auReturnpre);
//					bfree(B_L,b64en);
	                bfree(B_L,auReturn);
			        exit(0);
	            }else
				{
			        if (ioctl(wgfd, DWWD_GPIO_SET, &lock_ctl_value[gatenumber]) < 0)
		            {    
		                if(close(wgfd))
				        {
//					        printf("ioctl_err3 close gate[%d]\n",gatenumber);
							snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door%derr\",\"realm\":\"%s\",\"nonce\":\
			                    \"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		                    websEncode64(auReturn,auReturnpre,256);
							websText(wp);
	                        websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	                        websDone(wp, 200);
							bfree(B_L,authValue);
		                    bfree(B_L,nonce);
	                        bfree(B_L,expirytime);
		                    bfree(B_L,auReturnpre);
//							bfree(B_L,b64en);
	                        bfree(B_L,auReturn);
					        exit(0);
					    }
						snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door1open\",\"realm\":\"%s\",\"nonce\":\
				            \"%s\",\"expirytime\":\"%s\"}",websGetRealm(),nonce,expirytime);
//				        printf("gate[%d]_set_err index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
//			            sprintf(content,"gate[%d]_set_err index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
//			            dwwrite(content);
                        snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door%derr\",\"realm\":\"%s\",\"nonce\":\
			                \"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		                websEncode64(auReturn,auReturnpre,256);
						websText(wp);
	                    websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	                    websDone(wp, 200);
						bfree(B_L,authValue);
		                bfree(B_L,nonce);
	                    bfree(B_L,expirytime);
		                bfree(B_L,auReturnpre);
//                        bfree(B_L,b64en);
	                    bfree(B_L,auReturn);						
                        exit(0);
                    } else                    
					{
			            if(close(wgfd))
                        {
//					        printf("ioctl_err4 close gate[%d] \n",gatenumber);
							snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door%derr\",\"realm\":\"%s\",\"nonce\":\
			                    \"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		                    websEncode64(auReturn,auReturnpre,256);
//	                        printf("auReturn:%s\n",auReturn);    		
							websText(wp);
	                        websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	                        websDone(wp, 200);
							bfree(B_L,authValue);
		                    bfree(B_L,nonce);
	                        bfree(B_L,expirytime);
		                    bfree(B_L,auReturnpre);
//							bfree(B_L,b64en);
	                        bfree(B_L,auReturn);
			                exit(0);
						}
						snprintf(auReturnpre,255,"{\"result\":\"success\",\"actionReturn\":\"door%dopen\",\"realm\":\"%s\",\"nonce\":\
			                \"%s\",\"expirytime\":\"%s\"}",gatenumber+1,websGetRealm(),nonce,expirytime);
		                websEncode64(auReturn,auReturnpre,256);
//                    	printf("auReturn:%s\n",auReturn);    		
	                    websText(wp);
	                    websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	                    websDone(wp, 200);
						bfree(B_L,authValue);
		                bfree(B_L,nonce);
	                    bfree(B_L,expirytime);
		                bfree(B_L,auReturnpre);
//						bfree(B_L,b64en);
	                    bfree(B_L,auReturn);
//						printf("gate[%d] close index = %d,vaule = %d,\n",gatenumber,lock_ctl_value[gatenumber].index,lock_ctl_value[gatenumber].vaule);
			        }	 
		        }
		    }		
	    }
		exit(0);
	}	
    return;		
}

static void opendoor4jsonp(webs_t wp, char_t *path, char_t *query)
{
	int rc=0;
//	printf("query:%s len:%d\n",query,strlen(query));
	char_t* b64en;
	b64en = balloc(B_L,512);
	char_t* auReturn;
	auReturn=balloc(B_L,256);
    if(!query || (!strlen(query))) 
	{
	    snprintf(auReturn,255,"\"null\"");
//		printf("query:%s\n",query);
		websEncode64(b64en,auReturn,512);	   
	    websText(wp);
		websWrite(wp, T("authHandler(\"%s\");"),b64en);
//		printf("null:%s\n",b64en);
	    bfree(B_L,b64en);
        bfree(B_L,auReturn);		
	    return;	
	}
	char_t* strbuf;
	strbuf = balloc(B_L,512);	
	strcpy(strbuf,query);
	char_t* index1;
	char_t* index2;
	index1 = strchr(strbuf,'&')+1; 	
	if(index1==NULL)
    {
	    websText(wp);
		websWrite(wp, T("%s\n"),"no &");
		bfree(B_L,strbuf);
		return;
	}
	index2 = strchr(strbuf,'\0');	
	strncpy(strbuf,index1,index2-index1);
    index1 = strchr(strbuf,'&');
    *index1 =  '\0';    	
//	printf("%s\n",strbuf);
	char_t* b64de;
	b64de = balloc(B_L,512); 
	websDecode64(b64de,strbuf,512);
//	printf("authActin_Decode64:%s\n",b64de);
	char_t* aVindex1;
	aVindex1 = strstr(b64de,"\"authValue\":\"")+13;
	if(!aVindex1)
	{
		snprintf(auReturn,255,"\"NO_authValue\"");
		websEncode64(b64en,auReturn,512);
		websText(wp);
	    websWrite(wp, T("authHandler(\"%s\");"),b64en);
//		printf("aVindex1:%s NO_authValue:%s\n",aVindex1,b64en);
		bfree(B_L,strbuf);
	    bfree(B_L,b64de);
		bfree(B_L,auReturn);		
	    return;	
	}
	char_t* aVindex2;
	aVindex2=strchr(aVindex1,'"');
	if((aVindex2-aVindex1)!=32)
	{	    
		snprintf(auReturn,255,"\"authValue_32\"");
		websEncode64(b64en,auReturn,512);
		websText(wp);
	    websWrite(wp, T("authHandler(\"%s\");"),b64en);
//		printf("aVindex2:%s aVindex1:%s -:%d authValue_32:%s\n",aVindex2,aVindex1,(aVindex2-aVindex1),b64en);
		bfree(B_L,strbuf);
	    bfree(B_L,b64de);
		bfree(B_L,auReturn);		
	    return;	
	}
    char_t* authValue;
	authValue = balloc(B_L,40);
	strncpy(authValue,aVindex1,32);
	*(authValue+32) = '\0';
//	printf("authValue:%s\n",authValue);	
    char_t* username;
	username = balloc(B_L,24);	
	aVindex1 = strstr(b64de,"\"username\":\"");	
//	printf("aVindex1_usernmae:%s\n",aVindex1+12);
	strncpy(username,aVindex1+12,23);
	aVindex2 = strchr(username,'"');
	*aVindex2 = '\0';
//	printf("aVindex2_usernmae:%s\n",username);
//	printf("usernmae:%s\n",username);
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	unsigned char* staffnumbuff[3];
	staffnumbuff[0] = balloc(B_L,33);
	strcpy(staffnumbuff[0],"\0");
	staffnumbuff[1] = balloc(B_L,33);
	strcpy(staffnumbuff[1],"\0");
	staffnumbuff[2] = balloc(B_L,33);
	strcpy(staffnumbuff[2],"\0");
	rc = snprintf(sqlstr,255,"select distinct username, authValue,authSignature from staffumDb where username='%s';",username);
	rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
//	printf("username:%s authValue:%s authSignature:%s\n",staffnumbuff[0],staffnumbuff[1],staffnumbuff[2]);
	
	char_t* dindex1;
	char_t* dindex2;
	char_t* dindex3;
	char_t* dindex4;
	dindex1=strstr(b64de,"opendoor1");
	dindex2=strstr(b64de,"opendoor2");
    dindex3=strstr(b64de,"opendoor3");
    dindex4=strstr(b64de,"opendoor4");
    char_t* auReturnpre;
	auReturnpre=balloc(B_L,256);
	char_t *nonce;
	nonce = balloc(B_L,48);
	nonce = websCalcNonce(wp);
//	printf("nonce:%s\n",nonce);
	char_t* expirytime;
	expirytime=balloc(B_L,16);
	strcpy(expirytime,"1440");
//	printf("expirytime:%s\n",expirytime);	
	if(!strcmp(authValue,staffnumbuff[1]))
	{	    	    	    		
	    if (dindex1)
	    {
	        openclosegate4jsop(wp,0);
	    }else if(dindex2)
        {
	        openclosegate4jsop(wp,1);
	    }else if(dindex3)
        {
	        openclosegate4jsop(wp,2); 
	    }else if(dindex4)
		{
	        openclosegate4jsop(wp,3);
	    }else
	    {
//		    printf("EER:query == %s\n",b64de);
		}
	}else
    {	    
		if (dindex1)
	    {
		    snprintf(auReturnpre,255,"{\"result\":\"deny\",\"actionReturn\":\"door1err\",\"realm\":\"%s\",\"nonce\":\
			    \"%s\",\"expirytime\":\"%s\"}",websGetRealm(),nonce,expirytime);
		}else if(dindex2)
		{
		    snprintf(auReturnpre,255,"{\"result\":\"deny\",\"actionReturn\":\"door2err\",\"realm\":\"%s\",\"nonce\":\
		        \"%s\",\"expirytime\":\"%s\"}",websGetRealm(),nonce,expirytime);
		}else if(dindex3)
		{
		    snprintf(auReturnpre,255,"{\"result\":\"deny\",\"actionReturn\":\"door3err\",\"realm\":\"%s\",\"nonce\":\
		        \"%s\",\"expirytime\":\"%s\"}",websGetRealm(),nonce,expirytime); 
		}else if(dindex4)
		{
		    snprintf(auReturnpre,255,"{\"result\":\"deny\",\"actionReturn\":\"door4err\",\"realm\":\"%s\",\"nonce\":\
		        \"%s\",\"expirytime\":\"%s\"}",websGetRealm(),nonce,expirytime); 
		}
        websText(wp);
	    websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	    websDone(wp, 200);    		
	}	
//    printf("auReturnpre:%s\n",auReturnpre);
	websEncode64(auReturn,auReturnpre,256);
//	printf("auReturn:%s\n",auReturn);    		
	snprintf(auReturnpre,255,"{\"signature\":\"%s\",\"nonce\":\"%s\",\"expirytime\":\"%s\"}",staffnumbuff[2],nonce,expirytime);
	authValue=websMD5(auReturnpre);
	rc = snprintf(sqlstr,255,"update staffumDb set authValue='%s',nonce='%s',authExpirytime='%s' where username='%s';",authValue,nonce,expirytime,username);
	rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
//	printf("sqlstr:%s\n",sqlstr);	
	bfree(B_L,nonce);
	bfree(B_L,expirytime);
	bfree(B_L,auReturnpre);
	bfree(B_L,strbuf);
	bfree(B_L,b64de);
	bfree(B_L,b64en);
	bfree(B_L,auReturn);
	bfree(B_L,authValue);   
	bfree(B_L,username);
	bfree(B_L,staffnumbuff[0]);
	bfree(B_L,staffnumbuff[1]);
    bfree(B_L,staffnumbuff[2]);
	bfree(B_L,sqlstr);	
//	printf("opendoor4jsonp free ok...\n");
}

static void signatureCheck(webs_t wp, char_t *path, char_t *query)
{   
	char_t* strbuff;
	strbuff = balloc(B_L,256);	
	strcpy(strbuff,query);	
//    printf("strbuff:%s\n query:%s %d\n",strbuff,query,__LINE__);
	char_t* base64de;
	base64de = balloc(B_L,256);
	websDecode64(base64de,strbuff,256);
//	printf("base64de:%s %d\n",base64de,__LINE__);
    char_t* index1;
	index1 = strstr(base64de,"\"username\":\"");
    char_t* auReturnpre;
	auReturnpre=balloc(B_L,96);
	char_t* auReturn;
	auReturn=balloc(B_L,96);
	if(index1==NULL)
    {
	    snprintf(auReturnpre,95,"{\"res\":\"deny5\"}");
//		printf("auReturnpre:%s %d\n",auReturnpre,__LINE__);
//		snprintf(auReturn,95,auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
        websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp, 200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		return;
	}
	char_t* index2;
	index2=strchr(index1+12,'"');	
    char_t* wuName="\0";
	wuName=balloc(B_L,64);
	strncpy(wuName,index1+12,index2-(index1+12));
	strcpy(wuName+(index2-(index1+12)),"\0");
	if(!wuName||!(*wuName))
	{
	    snprintf(auReturnpre,95,"{\"res\":\"deny3\"}");
//		printf("auReturnpre:%s %d\n",auReturnpre,__LINE__);
//		snprintf(auReturn,95,auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
        websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,wuName);
		return;	
	}
	index1 = strstr(base64de,"\"password\":\""); 
	if(index1==NULL)
    {
	    snprintf(auReturnpre,95,"{\"res\":\"deny5\"}");
//		printf("auReturnpre:%s %d\n",auReturnpre,__LINE__);
//		snprintf(auReturn,95,auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp, 200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		return;
	}
	index2=strchr(index1+12,'"');
    char_t* wuSign="\0";	
	wuSign=balloc(B_L,64);
	strncpy(wuSign,index1+12,index2-(index1+12));
	strcpy(wuSign+(index2-(index1+12)),"\0");
	if(!wuSign||!(*wuSign))
	{
	    snprintf(auReturnpre,95,"{\"res\":\"deny4\"}");
//		printf("auReturnpre:%s %d\n",auReturnpre,__LINE__);
//		snprintf(auReturn,95,auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,wuName);
		bfree(B_L,wuSign);
		return;	
	}
//    printf("username:%s password0:%s %d\n",wuName,wuSign,__LINE__);	
    if(strlen(wuName)>24||strlen(wuSign)>48)
    {
        snprintf(auReturnpre,95,"{\"res\":\"deny6\"}");
//		printf("auReturnpre:%s %d\n",auReturnpre,__LINE__);
//		snprintf(auReturn,95,auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,wuName);
		bfree(B_L,wuSign);
//	    printf("username or password too long.\n");
	    return; 
    }
//	printf("username:%s password0:%s %d\n",wuName,wuSign,__LINE__);
    unsigned char* dbData[2];	
    dbData[0] = balloc(B_L,33);
    dbData[1] = balloc(B_L,33);
	if(!dbData[0]||!dbData[1]) perror("dbData");
    strcpy(dbData[0],"\0");
    strcpy(dbData[1],"\0");     
    char_t* sqls;
    sqls=balloc(B_L,128);
	if(!sqls) perror("sqls"); 
	int ncols=0,nrows=0;
    strcpy(sqls,"\0");    	
    snprintf(sqls,128,"select distinct staffname,signature from staffbasesetting where staffname=\"%.*s\";",strlen(wuName),wuName);
//	printf("db. %s dbData0:%p dbData1:%p %d\n",sqls,dbData[0],dbData[1],__LINE__);
	if(dwreadwriteDB(sqls,(unsigned char**)&dbData,&ncols,&nrows)<0) printf("db err. %s %d\n",sqls,__LINE__);
//	printf("sqls:%s %d\n",sqls,__LINE__);
//    printf("dbData0:%s %p dbData1:%s %p %d\n",dbData[0],dbData[0],dbData[1],dbData[1],__LINE__);
    if(!(*dbData[0]))
    {
        snprintf(auReturnpre,95,"{\"res\":\"deny1\"}");
		printf("auReturnpre:%s %d\n",auReturnpre,__LINE__);
		websEncode64(auReturn,auReturnpre,95);
//      snprintf(auReturn,95,auReturnpre);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,wuName);
		bfree(B_L,wuSign);
    	printf("username wrong. %d\n",__LINE__);
    	bfree(B_L,sqls);
    	bfree(B_L,dbData[1]);
    	bfree(B_L,dbData[0]);
    	return;
    }else
    {
	    if(strcmp(wuSign,dbData[1])==0) 
	    {
            snprintf(auReturnpre,95,"{\"res\":\"success\"}");
//		    printf("auReturnpre:%s\n",auReturnpre);
		    websEncode64(auReturn,auReturnpre,95);             
//          snprintf(auReturn,95,auReturnpre);
//			printf("auReturn:%s\n",auReturn);
//			websHeader(wp);
//		    websWrite(wp, T("@applicaiton/json:%s;charset=UTF-8\n"),auReturn);
//			websWrite(wp, T("%s"),"200");
//			websFooter(wp);           
//          websWrite(wp, T("HTTP/1.0 200 OK\n")); 
//          websWrite(wp, T("Server: %s\r\n"), WEBS_NAME);
//        	websWrite(wp, T("Pragma: no-cache\n"));
//	        websWrite(wp, T("Cache-control: no-cache\n"));
//	        websWrite(wp, T("Content-Type: applicaiton/json\n"));
//	        websWrite(wp, T("\n"));
            websText(wp);
            websWrite(wp, T("%s\n"),auReturn);
		    websDone(wp,200);		
	    }else
	    {
            snprintf(auReturnpre,95,"{\"res\":\"deny2\"}");
		    printf("auReturnpre:%s %d\n",auReturnpre,__LINE__);
		    websEncode64(auReturn,auReturnpre,95);
			websText(wp);
//          snprintf(auReturn,95,auReturnpre);
		    websWrite(wp, T("%s\n"),auReturn);
	        websDone(wp,200);
	        printf("password wrong. %d\n",__LINE__);
	    }
    }
    bfree(B_L,strbuff);
	bfree(B_L,auReturnpre);
	bfree(B_L,auReturn);
	bfree(B_L,base64de);
	bfree(B_L,wuName);
	bfree(B_L,wuSign);
    bfree(B_L,sqls);
    bfree(B_L,dbData[1]);
    bfree(B_L,dbData[0]);
}

#if (defined CONFIG_RALINK_WATCHDOG || defined CONFIG_RALINK_WATCHDOG_MODULE) && defined CONFIG_USER_WATCHDOG
static void WatchDogRestart(void)
{
	doSystem("killall -9 watchdog 1>/dev/null 2>&1");
	doSystem("rmmod ralink_wdt.o");
	if (strcmp(nvram_get(RT2860_NVRAM, "WatchDogEnable"), "1") == 0) {
		doSystem("insmod -q ralink_wdt.o");
		doSystem("wdg.sh");
		doSystem("watchdog");
	}
}
#endif

static void signatureChange(webs_t wp, char_t *path, char_t *query)
{

#if (defined CONFIG_RALINK_WATCHDOG || defined CONFIG_RALINK_WATCHDOG_MODULE) && defined CONFIG_USER_WATCHDOG
	char_t *watchdogcap;
	watchdogcap = websGetVar(wp, T("admwatchdog"), T(""));
//	printf("admwatchdog:%s\n",watchdogcap);
	nvram_bufset(RT2860_NVRAM, "WatchDogEnable", watchdogcap);
	nvram_commit(RT2860_NVRAM);
	WatchDogRestart();
#endif
    
	char_t* oName="0";
	char_t* oSign="0";
	char_t* wuName="0";
	char_t* wuSign="0";

    char_t* strbuff;
	strbuff = balloc(B_L,512);	
	strcpy(strbuff,query);	
//    printf("strbuff:%s\n query:%s\n",strbuff,query);
	char_t* base64de;
	base64de = balloc(B_L,512);
	websDecode64(base64de,strbuff,512);
//	printf("base64de:%s\n",base64de); 
    char_t* index1;
	index1 = strstr(base64de,"\"oadmuser\":\"");
    char_t* auReturnpre;
	auReturnpre=balloc(B_L,96);
	char_t* auReturn;
	auReturn=balloc(B_L,96);
	if(index1==NULL)
    {
	    snprintf(auReturnpre,95,"{\"result\":\"deny5\"}");
//		printf("auReturnpre0:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp, 200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		return;
	}
	char_t* index2;
	index2=strchr(index1+12,'"');	
	oName=balloc(B_L,64);
	if(index2)
	{
	    strncpy(oName,index1+12,index2-(index1+12));
	    strcpy(oName+(index2-(index1+12)),"\0");
	}
	if(!(*oName))
	{
	    snprintf(auReturnpre,95,"{\"result\":\"deny3\"}");
//		printf("auReturnpre1:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,oName);
		return;	
	}
	index1 = strstr(base64de,"\"oadmpass\":\""); 
	if(index1==NULL)
    {
	    snprintf(auReturnpre,95,"{\"result\":\"deny5\"}");
//		printf("auReturnpre2:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp, 200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		return;
	}
	index2=strchr(index1+12,'"');
	oSign=balloc(B_L,64);
	if(index2)
	{
	    strncpy(oSign,index1+12,index2-(index1+12));
	    strcpy(oSign+(index2-(index1+12)),"\0");
	}
	if(!(*oSign))
	{
	    snprintf(auReturnpre,95,"{\"result\":\"deny4\"}");
//		printf("auReturnpre3:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,oName);
		bfree(B_L,oSign);
		return;	
	}
	index1 = strstr(base64de,"\"admuser\":\""); 
	if(index1==NULL)
    {
	    snprintf(auReturnpre,95,"{\"result\":\"deny5\"}");
//		printf("auReturnpre4:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp, 200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		return;
	}
	index2=strchr(index1+11,'"');
	wuName=balloc(B_L,64);
	if(index2)
	{
	    strncpy(wuName,index1+11,index2-(index1+11));
	    strcpy(wuName+(index2-(index1+11)),"\0");
	}
	if(!(*wuName))
	{
	    snprintf(auReturnpre,95,"{\"result\":\"deny7\"}");
//		printf("auReturnpre5:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,oName);
		bfree(B_L,oSign);
		bfree(B_L,wuName);
		return;	
	}
	index1 = strstr(base64de,"\"admpass\":\""); 
	if(index1==NULL)
    {
	    snprintf(auReturnpre,95,"{\"result\":\"deny5\"}");
//		printf("auReturnpre8:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp, 200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		return;
	}
	index2=strchr(index1+11,'"');
	wuSign=balloc(B_L,64);
	if(index2)
	{
	    strncpy(wuSign,index1+11,index2-(index1+11));
	    strcpy(wuSign+(index2-(index1+11)),"\0");
	}
	if(!(*wuSign))
	{
	    snprintf(auReturnpre,95,"{\"result\":\"deny8\"}");
//		printf("auReturnpre9:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,oName);
		bfree(B_L,oSign);
		bfree(B_L,wuName);
		bfree(B_L,wuSign);
		return;	
	}
//    printf("oName:%s oSign:%s username:%s password0:%s\n",oName,oSign,wuName,wuSign);
    if(strlen(oName)>24||strlen(oSign)>48||strlen(wuName)>24||strlen(wuSign)>48)
	{
	    snprintf(auReturnpre,95,"{\"result\":\"deny6\"}");
//		printf("auReturnpre10:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,oName);
		bfree(B_L,oSign);
		bfree(B_L,wuName);
		bfree(B_L,wuSign);
		return;	 
	}
	char_t* oSigndecode;
	oSigndecode=balloc(B_L,48);
	websDecode64(oSigndecode,oSign,48);
	unsigned char* dbData[2];	
	dbData[0] = balloc(B_L,33);
	dbData[1] = balloc(B_L,33);
	strcpy(dbData[0],"\0");
    strcpy(dbData[1],"\0");
	char_t* sqls;
    sqls=balloc(B_L,256);
	int ncols=0,nrows=0;
    snprintf(sqls,255,"select distinct staffname,signature from staffbasesetting where staffname=\"%.*s\";",strlen(oName),oName);
	if(dwreadwriteDB(sqls,(unsigned char**)&dbData,&ncols,&nrows)<0) printf("signatureChange select err.\n");	
//	printf("dbData0:%s dbData1:%s\n",dbData[0],dbData[1]);
	if(!(*dbData[0]))
	{
	    snprintf(auReturnpre,95,"{\"result\":\"deny1\"}");
//		printf("auReturnpre11:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturnpre);
		bfree(B_L,auReturn);
		bfree(B_L,base64de);
		bfree(B_L,oName);
		bfree(B_L,oSign);
		bfree(B_L,wuName);
		bfree(B_L,wuSign);
		bfree(B_L,sqls);
	    bfree(B_L,dbData[1]);
	    bfree(B_L,dbData[0]);
	    bfree(B_L,oSigndecode);
		return;
	}else if(strcmp(oSigndecode,dbData[1])) 
	{
	    snprintf(auReturnpre,95,"{\"result\":\"deny2\"}");
//		printf("auReturnpre12:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
		websDone(wp,200);
		return;
	}else
	{
	    char_t* wuSigndecode;
	    wuSigndecode=balloc(B_L,48);
	    websDecode64(wuSigndecode,wuSign,48);
//	    printf("opassword1:%s password1:%s\n",oSigndecode,wuSigndecode);
		snprintf(sqls,255,"UPDATE staffbasesetting SET staffname='%s',signature='%s' WHERE staffname=\"%.*s\" ;",
		    wuName,wuSigndecode,strlen(oName),oName);
	    if(dwreadwriteDB(sqls,(unsigned char**)&dbData,&ncols,&nrows)<0) printf("signatureChange select1 err.\n");
		snprintf(sqls,255,"UPDATE attendanceoff SET staffname='%s' WHERE staffname=\"%.*s\";",wuName,
		    strlen(oName),oName);
	    if(dwreadwriteDB(sqls,(unsigned char**)&dbData,&ncols,&nrows)<0) printf("signatureChange select1 err.\n");		
		bfree(B_L,wuSigndecode);
		snprintf(auReturnpre,95,"{\"result\":\"success\"}");
//		printf("auReturnpre13:%s\n",auReturnpre);
		websEncode64(auReturn,auReturnpre,95);
		websText(wp);
		websWrite(wp, T("%s\n"),auReturn);
	    websDone(wp, 200);
    }
	bfree(B_L,strbuff);
	bfree(B_L,auReturnpre);
	bfree(B_L,auReturn);
	bfree(B_L,base64de);
	bfree(B_L,oName);
	bfree(B_L,oSign);
	bfree(B_L,wuName);
	bfree(B_L,wuSign);
	bfree(B_L,sqls);
    bfree(B_L,dbData[1]);
	bfree(B_L,dbData[0]);
	bfree(B_L,oSigndecode);
	return;
}

static void dwumDb(webs_t wp, char_t *path, char_t *query)
{
   	char_t* index1;
	char_t* strbuff;
	strbuff = balloc(B_L,512);
	char_t* auReturn;
	auReturn=balloc(B_L,256);
	strcpy(strbuff,query);	
//    printf("strbuff:%s\n query:%s\n",strbuff,query);
    index1 = strchr(strbuff,'&')+1; 	
	if(index1==NULL)
    {
	    websText(wp);
		websWrite(wp, T("%s\n"),"no &");
		websDone(wp, 200);
		bfree(B_L,strbuff);
		bfree(B_L,auReturn);
		return;
	}	
    int rc;
//	char_t* dValue;	
	char_t* index2;	  
//	dValue = balloc(B_L,256);
    index2 = strchr(strbuff,'\0');	
	strncpy(strbuff,index1,index2-index1);
    index1 = strchr(strbuff,'&');
    *index1 =  '\0';    	
//	printf("%s\n",strbuff);	
	char_t* base64de;
	base64de = balloc(B_L,512);
	char_t* base64en;
	base64en = balloc(B_L,512);
	websDecode64(base64de,strbuff,512);
//	printf("base64de:%s\n",base64de);
//    ws_set_cookie(wp,"userName","zpass",5,"/",NULL);
    char_t* aVindex1;
	aVindex1 = strstr(base64de,"\"authValue\":\"")+13;
	if(!aVindex1)
	{
		snprintf(auReturn,255,"\"NO_authValue\"");
		websEncode64(base64en,auReturn,512);
		websText(wp);
	    websWrite(wp, T("authHandler(\"%s\");"),base64en);
		websDone(wp, 200);
//		printf("aVindex1:%s NO_authValue:%s\n",aVindex1,base64en);
		bfree(B_L,strbuff);
	    bfree(B_L,base64de);
		bfree(B_L,auReturn);		
	    return;	
	}
	char_t* aVindex2;
	aVindex2=strchr(aVindex1,'"');
	if((aVindex2-aVindex1)!=32)
	{	    
		snprintf(auReturn,255,"\"authValue_32\"");
		websEncode64(base64en,auReturn,512);
		websText(wp);
	    websWrite(wp, T("authHandler(\"%s\");"),base64en);
		websDone(wp, 200);
//		printf("aVindex2:%s aVindex1:%s -:%d authValue_32:%s\n",aVindex2,aVindex1,(aVindex2-aVindex1),base64en);
		bfree(B_L,strbuff);
	    bfree(B_L,base64de);
		bfree(B_L,auReturn);		
	    return;	
	}
    char_t* authValue;
	authValue = balloc(B_L,40);
	strncpy(authValue,aVindex1,32);
	*(authValue+32) = '\0';
//	printf("authValue:%s\n",authValue);	
    char_t* username;
	username = balloc(B_L,24);	
	aVindex1 = strstr(base64de,"\"username\":\"");	
	strncpy(username,aVindex1+12,23);
	aVindex2 = strchr(username,'"');
	*aVindex2 = '\0';
//	printf("usernmae:%s\n",username);
	char_t* authChange;
	authChange=balloc(B_L,8);
//	strcpy(authChange,"\0");
	aVindex1 = strstr(base64de,"\"authChange\":\"");	
	strncpy(authChange,aVindex1+14,2);
	aVindex2 = strchr(authChange,'"');
	*aVindex2 = '\0';
//	printf("authChange:%s\n",authChange);
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	unsigned char* staffnumbuff[3];
	staffnumbuff[0] = balloc(B_L,33);
	strcpy(staffnumbuff[0],"\0");
	staffnumbuff[1] = balloc(B_L,33);
	strcpy(staffnumbuff[1],"\0");
	staffnumbuff[2] = balloc(B_L,33);
	strcpy(staffnumbuff[2],"\0");
	rc = snprintf(sqlstr,255,"select distinct username, authValue,authSignature from staffumDb where username='%s';",username);
	rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
//	printf("username:%s authValue:%s authSignature:%s\n",staffnumbuff[0],staffnumbuff[1],staffnumbuff[2]);	
    char_t *nonce;
	nonce = balloc(B_L,48);
	nonce = websCalcNonce(wp);
	char_t* expirytime;
	expirytime=balloc(B_L,16);
	strcpy(expirytime,"1440");
//	printf("expirytime:%s\n",expirytime);
	char_t* auReturnpre;
	auReturnpre=balloc(B_L,256);
	if(!strcmp(authValue,staffnumbuff[1]))
	{	  	    	  
	    if(!strcmp(authChange,"1"))
	    {
	        char_t* signature;
	        signature=balloc(B_L,40);
		    strcpy(signature,"\0");
            aVindex1 = strstr(base64de,"\"signature\":\"");	
	        strncpy(signature,aVindex1+13,36);
			aVindex2 = strchr(signature,'"');
	        *aVindex2 = '\0';
			char_t* Nsignature;
	        Nsignature=balloc(B_L,40);
		    strcpy(Nsignature,"\0");
            aVindex1 = strstr(base64de,"\"Nsignature\":\"");	
	        strncpy(Nsignature,aVindex1+14,36);
			aVindex2 = strchr(Nsignature,'"');
	        *aVindex2 = '\0';
//            printf("Nsignature:%s\n",Nsignature);
			char_t* Nusername;
	        Nusername = balloc(B_L,24);	
	        aVindex1 = strstr(base64de,"\"Nusername\":\"");	
	        strncpy(Nusername,aVindex1+13,23);
	        aVindex2 = strchr(Nusername,'"');
	        *aVindex2 = '\0';
//	        printf("Nusername:%s\n",Nusername);
            snprintf(auReturnpre,255,"{\"signature\":\"%s\",\"nonce\":\"%s\",\"expirytime\":\"%s\"}",Nsignature,nonce,expirytime);
	        authValue=websMD5(auReturnpre);
	        rc = snprintf(sqlstr,255,"update staffumDb set username='%s',authSignature='%s',authValue='%s',nonce='%s', authExpirytime='%s' where username='%s';",Nusername,Nsignature,authValue,nonce,expirytime,username);
	        rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
            bfree(B_L,signature);
			bfree(B_L,Nusername);
	        bfree(B_L,Nsignature);
	    }else if(!strcmp(authChange,"0")) 
        {
	       snprintf(auReturnpre,255,"{\"signature\":\"%s\",\"nonce\":\"%s\",\"expirytime\":\"%s\"}",staffnumbuff[2],nonce,expirytime);
	       authValue=websMD5(auReturnpre);
	       rc = snprintf(sqlstr,255,"update staffumDb set authValue='%s',nonce='%s', authExpirytime='%s' where username='%s';",authValue,nonce,expirytime,username);
	       rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
	    }
        snprintf(auReturnpre,255,"{\"result\":\"success\",\"realm\":\"%s\",\"nonce\":\"%s\",\"expirytime\":\"%s\"}",websGetRealm(),nonce,expirytime);		
	}else
	{
	    snprintf(auReturnpre,255,"{\"signature\":\"%s\",\"nonce\":\"%s\",\"expirytime\":\"%s\"}",staffnumbuff[2],nonce,expirytime);
	    authValue=websMD5(auReturnpre);
	    rc = snprintf(sqlstr,255,"update staffumDb set authValue='%s',nonce='%s', authExpirytime='%s' where username='%s';",authValue,nonce,expirytime,username);
		rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
		snprintf(auReturnpre,255,"{\"result\":\"deny\",\"realm\":\"%s\",\"nonce\":\"%s\",\"expirytime\":\"%s\"}",websGetRealm(),nonce,expirytime);
	}
//	printf("auReturnpre:%s\n",auReturnpre);
	websEncode64(auReturn,auReturnpre,256);
//	printf("auReturn:%s\n",auReturn);
	websText(wp);
	websWrite(wp, T("authHandler(\"%s\");"),auReturn);
	websDone(wp, 200);
//	printf("websDone\n");
	bfree(B_L,auReturnpre);
	bfree(B_L,auReturn);
    bfree(B_L,nonce);
	bfree(B_L,expirytime);
	bfree(B_L,strbuff);
	bfree(B_L,base64de);
    bfree(B_L,base64en);	
//	bfree(B_L,dValue);
	bfree(B_L,authValue);   
	bfree(B_L,username);
	bfree(B_L,staffnumbuff[0]);
	bfree(B_L,staffnumbuff[1]);
	bfree(B_L,sqlstr);
	bfree(B_L,authChange);	
//	printf("free ok\n");
}

static void setAttendance(webs_t wp, char_t *path, char_t *query)
{
    char_t*  content;
    content = balloc(B_L,64);
	char_t* sqlstr;
	sqlstr = balloc(B_L,512);
	int ncols=0,nrows=0;
	char_t* extenoflate;
	extenoflate = websGetVar(wp, T("extenoflate"), T("5"));
	char_t* extenofearly;
	extenofearly = websGetVar(wp, T("extenofearly"), T("5"));
	char_t* tolerateoflate;
	tolerateoflate = websGetVar(wp, T("tolerateoflate"), T("90"));
	char_t* tolerateofearly;
	tolerateofearly = websGetVar(wp, T("tolerateofearly"), T("90"));
	char_t* absentofworkaslate;
	absentofworkaslate = websGetVar(wp, T("absentofworkaslate"), T("0"));
	char_t* absentofworkasearly;
	absentofworkasearly = websGetVar(wp, T("absentofworkasearly"), T("0"));
	char_t* overtimeafter;
	overtimeafter = websGetVar(wp, T("overtimeafter"), T("60"));	
	char_t* swipe2card;
	swipe2card = websGetVar(wp, T("swipe2card"), T(""));
	char_t* swipe4card;
	swipe4card = websGetVar(wp, T("swipe4card"), T(""));
	char_t* workstart;
	workstart = websGetVar(wp, T("workstart"), T("08:30"));
	char_t* workoff;
	workoff = websGetVar(wp, T("workoff"), T("18:30"));
	char_t* morningworkoff;
	morningworkoff = websGetVar(wp, T("morningworkoff"), T("11:30"));
	char_t* afternoonworkstart;
	afternoonworkstart = websGetVar(wp, T("afternoonworkstart"), T("13:30"));
	char_t* saturdayrest;
	saturdayrest = websGetVar(wp, T("saturdayrest"), T("1"));
	char_t* saturdayamwork;
	saturdayamwork = websGetVar(wp, T("saturdayamwork"), T("0"));
	char_t* saturdaypmwork;
	saturdaypmwork = websGetVar(wp, T("saturdaypmwork"), T("0"));
	char_t* saturdayallwork;
	saturdayallwork = websGetVar(wp, T("saturdayallwork"), T("0"));
	char_t* sundayrest;
	sundayrest = websGetVar(wp, T("sundayrest"), T("1"));
	char_t* sundayamwork;
	sundayamwork = websGetVar(wp, T("sundayamwork"), T("0"));
	char_t* sundaypmwork;
	sundaypmwork = websGetVar(wp, T("sundaypmwork"), T("0"));
	char_t* sundayallwork;
	sundayallwork = websGetVar(wp, T("sundayallwork"), T("0"));
	char_t* swipecardnum;
	swipecardnum = balloc(B_L,8);
	if(!strcmp(swipe4card,"4")&&(!(*swipe2card)))
	{
	    strcpy(swipecardnum,"4");
	}else
	{
	    strcpy(swipecardnum,"2");
	}
//	printf("swipe2card:%s swipe4card:%s\n",swipe2card,swipe4card);
	char_t* buff;
	buff = balloc(B_L,33);
//	printf("extenoflate:%s extenofearly:%s tolerateoflate:%s tolerateofearly:%s absentofworkaslate:%s absentofworkasearly:%s overtimeafter:%s\n",
//	    extenoflate,extenofearly,tolerateoflate,tolerateofearly,absentofworkaslate,absentofworkasearly,overtimeafter);
	if((!extenoflate)||!(*extenoflate)||strlen(extenoflate)>8||(!extenofearly)||!(*extenofearly)||strlen(extenofearly)>8||
	    (!tolerateoflate)||!(*tolerateoflate)||strlen(tolerateoflate)>8||(!tolerateofearly)||!(*tolerateofearly)||
		strlen(tolerateofearly)>8||(!absentofworkaslate)||!(*absentofworkaslate)||(!absentofworkasearly)||!(*absentofworkasearly)||
		(!overtimeafter)||!(*overtimeafter)||strlen(overtimeafter)>8)
	{
	    printf("setAttendance_NULL or too long.\n");
//		sprintf(content,"setAttendance_NULL or too long.");
//		dwwrite(content);
		websText(wp);
		websWrite(wp, T("%s"),content);
//		websHeader(wp);			    
//		websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/attendancesetting.asp',3000);</script><br/>"));
//		websFooter(wp);
	    websDone(wp, 200);
	}else
	{   		
		snprintf(sqlstr,511,"update attendancesetting set extenoflate=%d,extenofearly=%d,tolerateoflate=%d,\
		    tolerateofearly=%d,absentofworkaslate='%s',absentofworkasearly='%s',swipecardnum=%d,workstart='%s',workoff='%s',\
			morningworkoff='%s',afternoonworkstart='%s',saturdayrest=%d,saturdayamwork=%d,saturdaypmwork=%d,saturdayallwork=%d,\
			sundayrest=%d,sundayamwork=%d,sundaypmwork=%d,sundayallwork=%d,overtimeafter=%d;",gatoi(extenoflate),gatoi(extenofearly),
			gatoi(tolerateoflate),gatoi(tolerateofearly),absentofworkaslate,absentofworkasearly,gatoi(swipecardnum),workstart,
			workoff,morningworkoff,afternoonworkstart,gatoi(saturdayrest),gatoi(saturdayamwork),gatoi(saturdaypmwork),
			gatoi(saturdayallwork),gatoi(sundayrest),gatoi(sundayamwork),gatoi(sundaypmwork),gatoi(sundayallwork),
			gatoi(overtimeafter));
	    websHeader(wp);
		if(dwreadwriteDB(sqlstr,(unsigned char**)&buff,&ncols,&nrows)<0) 
		    websWrite(wp, T("<script language=\"JavaScript\">alert('%s');</script><br/>"),"WRITE DB ERR.");	
        websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href=\"/door/attendancesetting.asp\",3000);</script><br/>"));		
	    websFooter(wp);
	    websDone(wp, 200);
	}
	bfree(B_L,sqlstr);	
	bfree(B_L,content);
	bfree(B_L,buff);
	bfree(B_L,swipecardnum); 
//	printf("setAttendance free ok.\n");
	return;
}

static int getabsentofworkaslate(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* absentofworkaslate;
	absentofworkaslate = balloc(B_L,33);
	strcpy(absentofworkaslate,"\0");
    strcpy(sqlstr,"select absentofworkaslate from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&absentofworkaslate,&ncols,&nrows);
	if(rc<0) printf("getabsentofworkaslate Db err.\n");
	rc = websWrite(wp, T("%s"),absentofworkaslate);
//	printf("absentofworkaslate:%s rc:%d\n",absentofworkaslate,rc);
	bfree(B_L,absentofworkaslate);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getabsentofworkasearly(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* absentofworkasearly;
	absentofworkasearly = balloc(B_L,33);
	strcpy(absentofworkasearly,"\0");
    strcpy(sqlstr,"select absentofworkasearly from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&absentofworkasearly,&ncols,&nrows);
	if(rc<0) printf("getabsentofworkasearly Db err.\n");
	rc = websWrite(wp, T("%s"),absentofworkasearly);
//	printf("absentofworkasearly:%s rc:%d\n",absentofworkasearly,rc);
	bfree(B_L,absentofworkasearly);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getExtenoflate(int eid, webs_t wp, int argc, char_t **argv)
{
//	printf("getExtenoflate......\n");
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* extenoflate;
	extenoflate = balloc(B_L,33);
	strcpy(extenoflate,"\0");
    strcpy(sqlstr,"select extenoflate from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&extenoflate,&ncols,&nrows);
	if(rc<0) printf("getextenoflate Db err.\n");
	rc = websWrite(wp, T("%s"),extenoflate);
//	printf("extenoflate:%s rc:%d\n",extenoflate,rc);
	bfree(B_L,extenoflate);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getExtenofearly(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* extenofearly;
	extenofearly = balloc(B_L,33);
    strcpy(sqlstr,"select extenofearly from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&extenofearly,&ncols,&nrows);
	if(rc<0) printf("getextenofearly Db err.\n");
	rc = websWrite(wp, T("%s"),extenofearly);
//	printf("extenofearly:%s rc:%d\n",extenofearly,rc);
	bfree(B_L,extenofearly);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getTolerateoflate(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* tolerateoflate;
	tolerateoflate = balloc(B_L,33);
    strcpy(sqlstr,"select tolerateoflate from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&tolerateoflate,&ncols,&nrows);
	if(rc<0) printf("gettolerateoflate Db err.\n");
	rc = websWrite(wp, T("%s"),tolerateoflate);
//	printf("tolerateoflate:%s rc:%d\n",tolerateoflate,rc);
	bfree(B_L,tolerateoflate);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getTolerateofearly(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* tolerateofearly;
	tolerateofearly = balloc(B_L,33);
    strcpy(sqlstr,"select tolerateofearly from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&tolerateofearly,&ncols,&nrows);
	if(rc<0) printf("gettolerateofearly Db err.\n");
	rc = websWrite(wp, T("%s"),tolerateofearly);
//	printf("tolerateofearly:%s rc:%d\n",tolerateofearly,rc);
	bfree(B_L,tolerateofearly);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getOvertimeafter(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* overtimeafter;
	overtimeafter = balloc(B_L,33);
	strcpy(overtimeafter,"\0");
    strcpy(sqlstr,"select overtimeafter from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&overtimeafter,&ncols,&nrows);
	if(rc<0) printf("overtimeafter Db err.\n");
	rc = websWrite(wp, T("%s"),overtimeafter);
//	printf("overtimeafter:%s rc:%d\n",overtimeafter,rc);
	bfree(B_L,overtimeafter);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getWorkstart(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* workstart;
	workstart = balloc(B_L,33);
	strcpy(workstart,"\0");
    strcpy(sqlstr,"select workstart from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&workstart,&ncols,&nrows);
	if(rc<0) printf("workstart Db err.\n");
	rc = websWrite(wp, T("%s"),workstart);
//	printf("workstart:%s rc:%d\n",workstart,rc);
	bfree(B_L,workstart);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getWorkoff(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* workoff;
	workoff = balloc(B_L,33);
	strcpy(workoff,"\0");
    strcpy(sqlstr,"select workoff from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&workoff,&ncols,&nrows);
	if(rc<0) printf("workoff Db err.\n");
	rc = websWrite(wp, T("%s"),workoff);
//	printf("workoff:%s rc:%d\n",workoff,rc);
	bfree(B_L,workoff);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getmorningWorkoff(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* morningworkoff;
	morningworkoff = balloc(B_L,33);
	strcpy(morningworkoff,"\0");
    strcpy(sqlstr,"select morningworkoff from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&morningworkoff,&ncols,&nrows);
	if(rc<0) printf("morningworkoff Db err.\n");
	rc = websWrite(wp, T("%s"),morningworkoff);
//	printf("workoff:%s rc:%d\n",morningworkoff,rc);
	bfree(B_L,morningworkoff);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getafternoonWorkstart(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* afternoonworkstart;
	afternoonworkstart = balloc(B_L,33);
	strcpy(afternoonworkstart,"\0");
    strcpy(sqlstr,"select afternoonworkstart from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	int rc = dwreadwriteDB(sqlstr,(unsigned char**)&afternoonworkstart,&ncols,&nrows);
	if(rc<0) printf("afternoonworkstart Db err.\n");
	rc = websWrite(wp, T("%s"),afternoonworkstart);
//	printf("afternoonworkstart:%s rc:%d\n",afternoonworkstart,rc);
	bfree(B_L,afternoonworkstart);
	bfree(B_L,sqlstr);
	return  rc;
}

static int dwreadholiday(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* s;
	s = balloc(B_L,49);	
	char_t* sqlstr;
	int ncols=0,nrows=0;
	sqlstr = balloc(B_L,256);
	char_t* staffbasesettingtab;
	staffbasesettingtab = balloc(B_L,2048);
	strcpy(staffbasesettingtab,"{\0");
	char_t* dbResult[112];
	static unsigned char i,j;
	for(i=0;i<112;i++)
	{
	    dbResult[i] = balloc(B_L,33);	
	} 
	snprintf(sqlstr,255,"select rowid,holidayname,holidayfrom,holidayto,holidaynote from attendanceholiday;");
//    printf("sqlstr:%s\n",sqlstr);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&dbResult,&ncols,&nrows)<0) printf("dwreadstaff select1 err.\n");
//	printf("nrows=%d,ncols=%d\n",nrows,ncols);	
	for(i=1;i<=nrows;i++)
	{
	    for(j=1;j<=ncols;j++)
		{
//			if(i==1&&j==1)
//			{
//			    sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"s%d_%d\":\"%s\""
//     				,nrows,ncols,i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
//			    strcat(staffbasesettingtab,s);
//		    }else
//			{
			    snprintf(s,48,"\"s%d_%d\":\"%s\",",i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
			    strcat(staffbasesettingtab,s);
				if(strlen(staffbasesettingtab)>=1952) break;
//			}
		}		
	}
	snprintf(s,48,"\"nrows\":\"%d\",\"ncols\":\"%d\"}",nrows,ncols);
	strcat(staffbasesettingtab,sqlstr);
//    printf("%s\n",staffbasesettingtab);	
	websWrite(wp, T("%s"),staffbasesettingtab);
	for(i=0;i<112;i++)
	{
	    bfree(B_L,dbResult[i]);
	}
	bfree(B_L,s);
	bfree(B_L,staffbasesettingtab);
	bfree(B_L,sqlstr);
	return 0;
}

static void dwDelholiday(webs_t wp, char_t *path, char_t *query)
{
//    printf("%s\n",query);
    websText(wp); 	
	if(!query || (!strlen(query)))
	{	    
		websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
	char_t* rtl;
    rtl = balloc(B_L,33);
	int ncols=0,nrows=0;
	if(dwreadwriteDB(query,(unsigned char**)&rtl,&ncols,&nrows)<0) 
	{
//	    printf("dwDelholiday delete err.\n");
	    websWrite(wp, T("%s"),"dwDelholiday err.");
	}else
	{
//	    websHeader(wp);
//       websWrite(wp, T("HTTP/1.0 200 OK\n"));		
    }
	websDone(wp, 200);
	bfree(B_L,rtl);
}

static void dwwriteholiday(webs_t wp, char_t *path, char_t *query)
{
	char_t*  content;
    content = balloc(B_L,64);
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* holidayname = "\0";
	char_t* holidayfrom = "\0";
	char_t* holidayto = "\0";
	char_t* holidaynote = "null";
	int rc = 0;
    unsigned char* staffnumbuff[1];
	staffnumbuff[0] = balloc(B_L,33);
	holidayname = websGetVar(wp, T("holidayname"), T(""));
	holidayfrom = websGetVar(wp, T("holidayfrom"), T(""));
	holidayto = websGetVar(wp, T("holidayto"), T(""));
	holidaynote = websGetVar(wp, T("holidaynote"), T(""));
//	printf("holidayname:%s,holidayfrom:%s,holidayto:%s,holidaynote:%s\n",holidayname,holidayfrom,holidayto,holidaynote);
	if(!(*holidayname)||!(*holidayfrom)||!(*holidayto)
	    ||strlen(holidayname)>18||strlen(holidayfrom)>21||strlen(holidayto)>21||strlen(holidaynote)>28)
	{
//	    printf("dwwriteholiday_NULL.\n");
//		sprintf(content,"dwwriteholiday_NULL or too long.");
//		dwwrite(content);
		sprintf(content,"INPUT NULL or too long.");
		websHeader(wp);
		websWrite(wp, T("%s<br/>"),content);
		websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href=\"/door/attendanceholiday.asp\",5000);</script><br/>"));			    
		websFooter(wp);
	    websDone(wp, 200);
	}else
	{
	    rc = snprintf(sqlstr,255,"select distinct holidayname from attendanceholiday where holidayname='%s';",
		    holidayname);
        rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
//		printf("dwreadDB=%d\n",rc);
		if(strcmp(*staffnumbuff,holidayname)==0)
		{
//		    sprintf(content,"holidayname is repeat,Please rename.");
			sprintf(content,"节假日名称重复，请重命名。");            //don't use '' instead of ""
		    websHeader(wp);		
	        websWrite(wp, T("<script language=\"JavaScript\">alert('%s');</script><br/>"),content);
			websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href=\"/door/attendanceholiday.asp\",5000);</script><br/>"));
		    websFooter(wp);
	        websDone(wp, 200);
			bfree(B_L,staffnumbuff[0]);
	        bfree(B_L,content);
	        bfree(B_L,sqlstr);
			return;
		}
		if(rc!= -1)
		{
		    rc = snprintf(sqlstr,255,"INSERT INTO attendanceholiday(holidayname,holidayfrom,holidayto,holidaynote)\
			    VALUES(\"%s\",\"%s\",\"%s\",\"%s\");",holidayname,holidayfrom,holidayto,holidaynote);
	        websHeader(wp);
		    if(dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows)<0) websWrite(wp, T("%s<br/>"),"WRITE DB ERR.");
            websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href=\"/door/attendanceholiday.asp\",3000);</script><br/>"));			
	        websFooter(wp);
	        websDone(wp, 200);
		}        		
    }
	bfree(B_L,staffnumbuff[0]);
	bfree(B_L,content);
	bfree(B_L,sqlstr);
//	printf("free staffnumbuff[0] ok\n");
}

static int getsaturdayRest(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* saturdayRest;
	saturdayRest = balloc(B_L,33);
    strcpy(sqlstr,"select saturdayrest from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&saturdayRest,&ncols,&nrows)<0) printf("saturdayRest Db err.\n");
//	printf("saturdayRest=%s\n",saturdayRest);
	int rc = websWrite(wp, T("%s"),saturdayRest);
	bfree(B_L,saturdayRest);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getsaturdayAmwork(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* saturdayAmwork;
	saturdayAmwork = balloc(B_L,33);
    strcpy(sqlstr,"select saturdayAmwork from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&saturdayAmwork,&ncols,&nrows)<0) printf("saturdayAmwork Db err.\n");
//	printf("saturdayAmwork=%s\n",saturdayAmwork);
	int rc = websWrite(wp, T("%s"),saturdayAmwork);
	bfree(B_L,saturdayAmwork);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getsaturdayPmwork(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* saturdayPmwork;
	saturdayPmwork = balloc(B_L,33);
    strcpy(sqlstr,"select saturdayPmwork from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&saturdayPmwork,&ncols,&nrows)<0) printf("saturdayPmwork Db err.\n");
//	printf("saturdayPmwork=%s\n",saturdayPmwork);
	int rc = websWrite(wp, T("%s"),saturdayPmwork);
	bfree(B_L,saturdayPmwork);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getsaturdayAllwork(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* saturdayAllwork;
	saturdayAllwork = balloc(B_L,33);
    strcpy(sqlstr,"select saturdayAllwork from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&saturdayAllwork,&ncols,&nrows)<0) printf("saturdayAllwork Db err.\n");
//	printf("saturdayAllwork=%s\n",saturdayAllwork);
	int rc = websWrite(wp, T("%s"),saturdayAllwork);
	bfree(B_L,saturdayAllwork);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getsundayRest(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* sundayRest;
	sundayRest = balloc(B_L,33);
    strcpy(sqlstr,"select sundayrest from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&sundayRest,&ncols,&nrows)<0) printf("sundayRest Db err.\n");
//	printf("sundayRest=%s\n",sundayRest);
	int rc = websWrite(wp, T("%s"),sundayRest);
	bfree(B_L,sundayRest);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getsundayAmwork(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* sundayAmwork;
	sundayAmwork = balloc(B_L,33);
    strcpy(sqlstr,"select sundayAmwork from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&sundayAmwork,&ncols,&nrows)<0) printf("sundayAmwork Db err.\n");
//	printf("sundayAmwork=%s\n",sundayAmwork);
	int rc = websWrite(wp, T("%s"),sundayAmwork);
	bfree(B_L,sundayAmwork);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getsundayPmwork(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* sundayPmwork;
	sundayPmwork = balloc(B_L,33);
    strcpy(sqlstr,"select sundayPmwork from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&sundayPmwork,&ncols,&nrows)<0) printf("sundayPmwork Db err.\n");
//	printf("sundayPmwork=%s\n",sundayPmwork);
	int rc = websWrite(wp, T("%s"),sundayPmwork);
	bfree(B_L,sundayPmwork);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getsundayAllwork(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* sundayAllwork;
	sundayAllwork = balloc(B_L,33);
    strcpy(sqlstr,"select sundayAllwork from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&sundayAllwork,&ncols,&nrows)<0) printf("sundayAllwork Db err.\n");
//	printf("sundayAllwork=%s\n",sundayAllwork);
	int rc = websWrite(wp, T("%s"),sundayAllwork);
	bfree(B_L,sundayAllwork);
	bfree(B_L,sqlstr);
	return  rc;
}

static int getswipecardnum(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* swipecardnum;
	swipecardnum = balloc(B_L,33);
    strcpy(sqlstr,"select swipecardnum from attendancesetting where rowid = (select max(rowid) from attendancesetting);");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&swipecardnum,&ncols,&nrows)<0) printf("swipecardnum Db err.\n");
//	printf("swipecardnum=%s\n",swipecardnum);
	int rc = websWrite(wp, T("%s"),swipecardnum);
	bfree(B_L,swipecardnum);
	bfree(B_L,sqlstr);
	return  rc;
}

char t2pagenum=1;
static int dwreadoff(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* s;
	s = balloc(B_L,95);	
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* staffbasesettingtab;
	staffbasesettingtab = balloc(B_L,2048);
	strcpy(staffbasesettingtab,"{\0");
	char_t* dbResult[100];
	static unsigned char i,j;
	for(i=0;i<100;i++)
	{
	    dbResult[i] = balloc(B_L,33);	
	} 
	int pagestart=1;
	int pageend=1;
	char_t* rowsnum;
	rowsnum = balloc(B_L,33);	
	strcpy(sqlstr,"select COUNT(*) from attendanceoff;");
	if(dwreadwriteDB(sqlstr,(unsigned char**)&rowsnum,&ncols,&nrows)<0) printf("dwreadoff select0 err.\n");
//	printf("rowsnum=%s\n",rowsnum);
//	if(gatoi(rowsnum))
//	{
	    int t2pagemax=1;
	    t2pagemax = (((gatoi(rowsnum))/14.0)-(int)((gatoi(rowsnum))/14.0))>0.?(int)((gatoi(rowsnum))/14.0)+1:(int)((gatoi(rowsnum))/14.0);	
	    if(t2pagemax<1) t2pagemax=1;
//	    printf("t2pagemax=%d\n",t2pagemax);
	    if(t2pagenum>t2pagemax) t2pagenum=t2pagemax;
	    pagestart=14*t2pagenum-14;
        pageend=14;	
	    snprintf(sqlstr,255,"select rowid,staffnum,staffname,departmentname,typeofoff,startofoff,endofoff from attendanceoff limit %d,%d;",pagestart,pageend);
//        printf("sqlstr:%s\n",sqlstr);
	    if(dwreadwriteDB(sqlstr,(unsigned char**)&dbResult,&ncols,&nrows)<0) printf("dwreadoff select1 err.\n");
//	    printf("nrows=%d,ncols=%d\n",nrows,ncols);	
	    for(i=1;i<=nrows;i++)
	    {
	        for(j=1;j<=ncols;j++)
		    {
//			    if(i==1&&j==1)
//			    {
//			        sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"t2pagemax\":\"%d\",\"t2pagenum\":\"%d\",\"s%d_%d\":\"%s\""
//     				    ,nrows,ncols,t2pagemax,t2pagenum,i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
//			        strcat(staffbasesettingtab,s);
//		        }else
//			    {
			        snprintf(s,48,"\"s%d_%d\":\"%s\",",i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
			        strcat(staffbasesettingtab,s);
					if(strlen(staffbasesettingtab)>=1905) break;
//			    }
		    }		
	    }
		snprintf(sqlstr,95,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"t2pagemax\":\"%d\",\"t2pagenum\":\"%d\"}",nrows,ncols,t2pagemax,t2pagenum);
//    }
//	else
//    {
//	    snprintf(staffbasesettingtab,64,"{\"nrows\":\"0\",\"ncols\":\"0\",\"t2pagemax\":\"1\",\"t2pagenum\":\"1\"");
//	}	
	strcat(staffbasesettingtab,sqlstr);
//    printf("%s\n",staffbasesettingtab);	
	websWrite(wp, T("%s"),staffbasesettingtab);
	for(i=0;i<100;i++)
	{
	    bfree(B_L,dbResult[i]);
	}
	bfree(B_L,s);
	bfree(B_L,staffbasesettingtab);
	bfree(B_L,sqlstr);
	return 0;
}

static void dwsett2off(webs_t wp, char_t *path, char_t *query)
{
	websText(wp);
	if(!query || (!strlen(query)))
	{
	    websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
	if(gatoi(query)>=1) t2pagenum=gatoi(query);
//	printf("query:%s t2pagenum:%d\n",query,t2pagenum);
//	websWrite(wp, T("%s"),"200");
	websDone(wp, 200);
}

static int getDpSelection(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* s;
	s = balloc(B_L,49);	
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* DpSelectiontab;
	DpSelectiontab = balloc(B_L,1160);
	strcpy(DpSelectiontab,"{\0");
//	printf("DpSelectiontab:%s\n",DpSelectiontab);
	char_t* DptSelection[48];
	int i,j;
	for(i=0;i<48;i++)
	{
	    DptSelection[i] = balloc(B_L,33);
    }
	strcpy(sqlstr,"select distinct departmentname from staffbasesetting;");	
	if(dwreadwriteDB(sqlstr,(unsigned char**)&DptSelection,&ncols,&nrows)<0) printf("DptSelection Db err.\n");
//	printf("nrows=%d,ncols=%d\n",nrows,ncols);
	for(i=1;i<=nrows;i++)
	{
	    for(j=1;j<=ncols;j++)
		{
//			if(i==1&&j==1)
//			{
//			    sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"s%d_%d\":\"%s\""
//     				,nrows,ncols,i,j-1,*(DptSelection+((i-1)*ncols)+(j-1)));
//			    strcat(DpSelectiontab,s);
//		    }else
//			{
			    snprintf(s,48,"\"s%d_%d\":\"%s\",",i,j-1,*(DptSelection+((i-1)*ncols)+(j-1)));
			    strcat(DpSelectiontab,s);
				if(strlen(DpSelectiontab)>=1064) break;
//			}
		}		
	}
	snprintf(sqlstr,48,"\"nrows\":\"%d\",\"ncols\":\"%d\"}",nrows,ncols);	
	strcat(DpSelectiontab,sqlstr);
//    printf("%s\n",DpSelectiontab);	
	int rc = websWrite(wp, T("%s"),DpSelectiontab);
	for(i=0;i<48;i++)
	{
	    bfree(B_L,DptSelection[i]);
	}
	bfree(B_L,sqlstr);
	bfree(B_L,DpSelectiontab);
	bfree(B_L,s);
	return  rc;
}

static void dwreadStaffoff(webs_t wp, char_t *path, char_t *query)
{   
	if(!query || (!strlen(query)))
	{
	    websText(wp);
		websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
	char_t* s;
	s = balloc(B_L,128);	
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* staffofftab;
	staffofftab = balloc(B_L,2048);
	strcpy(staffofftab,"{\0");
	char_t* dbResult[112];
	int pagestart=1;
	int pageend=1;
	static unsigned char i,j;
	for(i=0;i<112;i++)
	{
	    dbResult[i] = balloc(B_L,33);	
	}
	char_t* rowsnum;
	rowsnum = balloc(B_L,33);	
	strcpy(sqlstr,"select COUNT(*) from staffbasesetting;");
	if(dwreadwriteDB(sqlstr,(unsigned char**)&rowsnum,&ncols,&nrows)<0) printf("dwreadStaffoff select0 err.\n");
//	printf("rowsnum=%s\n",rowsnum);
	int pagemax=1;
	pagemax = (((gatoi(rowsnum))/28.0)-(int)((gatoi(rowsnum))/28.0))>0.?(int)((gatoi(rowsnum))/28.0)+1:(int)((gatoi(rowsnum))/28.0);	
	if(pagemax<1) pagemax=1;
//	printf("pagemax=%d\n",pagemax);
	char offpagenum=1;
	char_t* dpSelection;
	dpSelection = balloc(B_L,24);
	char_t* strbuf;
	strbuf = balloc(B_L,48);
	strcpy(strbuf,query);
	char_t* sIndex1;
	char_t* sIndex2;
    if(strstr(strbuf,"dpSelection"))
	{
	    sIndex1=strstr(strbuf,"dpSelection")+14;
//		printf("strbuf1:%s\n",strbuf);
        strncpy(dpSelection,sIndex1,23);
        sIndex2=strchr(dpSelection,'"');
        *(sIndex2)='\0';
//        printf("dpSelection:%s \n",dpSelection);
//        strcpy(dpSelection,strbuf);		
	}else if(strstr(strbuf,"offpagenum"))
	{
	    sIndex1=strstr(strbuf,"offpagenum")+13;
//		printf("strbuf1:%s\n",strbuf);
        strcpy(strbuf,sIndex1);
        sIndex2=strchr(strbuf,'"');
        *(sIndex2)='\0';
//        printf("strbuf2:%s\n",strbuf);	
		offpagenum=gatoi(strbuf);
	}		
	if(offpagenum>pagemax) offpagenum=pagemax;
	pagestart=28*offpagenum-28;
    pageend=28;		
//	printf("dpSelection:%s\n",dpSelection);	
	snprintf(sqlstr,255,"select rowid,staffnum,staffname,departmentname from staffbasesetting where \
	    departmentname='%s' limit %d,%d;",dpSelection,pagestart,pageend);
//    printf("sqlstr:%s\n",sqlstr);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&dbResult,&ncols,&nrows)<0) printf("dwreadstaffoff select1 err.\n");
//	printf("nrows=%d,ncols=%d\n",nrows,ncols);	
	for(i=1;i<=nrows;i++)
	{
	    for(j=1;j<=ncols;j++)
		{
//			if(i==1&&j==1)
//			{
//			    sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"pagemax\":\"%d\",\"offpagenum\":\"%d\",\
				    \"ss%d_%d\":\"%s\"",nrows,ncols,pagemax,offpagenum,i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
//			    strcat(staffofftab,s);
//		    }else
//			{
			    snprintf(s,48,"\"ss%d_%d\":\"%s\",",i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
			    strcat(staffofftab,s);
				if(strlen(staffofftab)>=1905) break;
//			}
		}		
	}
	snprintf(sqlstr,95,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"pagemax\":\"%d\",\"offpagenum\":\"%d\"}",nrows,ncols,pagemax,offpagenum);
	strcat(staffofftab,sqlstr);
//    printf("%s\n",staffofftab);
    websJson(wp);	
	websWrite(wp, T("%s"),staffofftab);
	websDone(wp, 200);
	for(i=0;i<112;i++)
	{
	    bfree(B_L,dbResult[i]);
	}
	bfree(B_L,s);
	bfree(B_L,staffofftab);
	bfree(B_L,sqlstr);
	bfree(B_L,dpSelection);
	bfree(B_L,strbuf);
//	printf("dwreadStaffoff bfree ok.\n");
	return;
}

static void dwwriteoff(webs_t wp, char_t *path, char_t *query)
{
	websText(wp);
	if(!query || (!strlen(query)))
	{	    
		websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
	char_t* strbuf;
	strbuf = balloc(B_L,512);
	strcpy(strbuf,query);
	char_t* base64de;
	base64de = balloc(B_L,512);
	websDecode64(base64de,strbuf,512);
//	printf("base64de:%s\n",base64de);
	char_t* oindex1;
    oindex1=strstr(base64de,"\"staffnum\":\"");
	char_t* qReturnpre;
	qReturnpre=balloc(B_L,96);
	char_t* qReturn;
	qReturn=balloc(B_L,96);
	if(oindex1==NULL)
    {
	    snprintf(qReturnpre,95,"{\"result\":\"fail_5\"}");
//		printf("qReturnpre1:%s\n",qReturnpre);
		websEncode64(qReturn,qReturnpre,95);
		websWrite(wp, T("%s\n"),qReturn);
		websDone(wp, 200);
		bfree(B_L,strbuf);
		bfree(B_L,qReturnpre);
		bfree(B_L,qReturn);
		bfree(B_L,base64de);
		return;
	}  
	char_t* oindex2;
	oindex2=strchr(oindex1+12,'"');
    char_t* staffnum = "\0";	
	staffnum=balloc(B_L,64);
	strcpy(strbuf,"\0");
	strncpy(strbuf,oindex1+12,oindex2-(oindex1+12));
	strcpy(strbuf+(oindex2-(oindex1+12)),"\0");	
	websDecode64(staffnum,strbuf,64);
//	printf("staffnum:%s\n",staffnum);
    oindex1=strstr(base64de,"\"staffname\":\"");
	if(oindex1==NULL)
    {
	    snprintf(qReturnpre,95,"{\"result\":\"fail_5\"}");
//		printf("qReturnpre2:%s\n",qReturnpre);
		websEncode64(qReturn,qReturnpre,95);
		websWrite(wp, T("%s\n"),qReturn);
		websDone(wp, 200);
		bfree(B_L,strbuf);
		bfree(B_L,qReturnpre);
		bfree(B_L,qReturn);
		bfree(B_L,base64de);
		bfree(B_L,staffnum);
		return;
	} 
	oindex2=strchr(oindex1+13,'"');
    char_t* staffname = "\0";	
	staffname = balloc(B_L,64);
	strcpy(strbuf,"\0");
	strncpy(strbuf,oindex1+13,oindex2-(oindex1+13));
	strcpy(strbuf+(oindex2-(oindex1+13)),"\0");
//	printf("staffnum1:%s\n",strbuf);
	websDecode64(staffname,strbuf,64);
//	printf("staffname:%s \n",staffname);
	oindex1=strstr(base64de,"\"staffdp\":\"");
	if(oindex1==NULL)
    {
	    snprintf(qReturnpre,95,"{\"result\":\"fail_5\"}");
//		printf("qReturnpre3:%s\n",qReturnpre);
		websEncode64(qReturn,qReturnpre,95);
		websWrite(wp, T("%s\n"),qReturn);
		websDone(wp, 200);
		bfree(B_L,strbuf);
		bfree(B_L,qReturnpre);
		bfree(B_L,qReturn);
		bfree(B_L,base64de);
		bfree(B_L,staffnum);
		bfree(B_L,staffname);
		return;
	} 
	oindex2=strchr(oindex1+11,'"');
    char_t* staffdp = "\0";	
	staffdp = balloc(B_L,64);
	strcpy(strbuf,"\0");
	strncpy(strbuf,oindex1+11,oindex2-(oindex1+11));
	strcpy(strbuf+(oindex2-(oindex1+11)),"\0");
//	printf("staffdp1:%s\n",strbuf);
	websDecode64(staffdp,strbuf,64);
//	printf("staffdp:%s\n",staffdp);
	oindex1=strstr(base64de,"\"off_type\":\"");
	if(oindex1==NULL)
    {
	    snprintf(qReturnpre,95,"{\"result\":\"fail_5\"}");
//		printf("qReturnpre4:%s\n",qReturnpre);
		websEncode64(qReturn,qReturnpre,95);
		websWrite(wp, T("%s\n"),qReturn);
		websDone(wp, 200);
		bfree(B_L,strbuf);
		bfree(B_L,qReturnpre);
		bfree(B_L,qReturn);
		bfree(B_L,base64de);
		bfree(B_L,staffnum);
		bfree(B_L,staffname);
		bfree(B_L,staffdp);
		return;
	} 
	oindex2=strchr(oindex1+12,'"');
    char_t* off_type = "\0";	
	off_type = balloc(B_L,64);
	strcpy(strbuf,"\0");
	strncpy(strbuf,oindex1+12,oindex2-(oindex1+12));
	strcpy(strbuf+(oindex2-(oindex1+12)),"\0");
//	printf("off_type1:%s\n",strbuf);
	websDecode64(off_type,strbuf,64);
//	printf("off_type:%s\n",off_type);
	oindex1=strstr(base64de,"\"off_from\":\"");
	if(oindex1==NULL)
    {
	    snprintf(qReturnpre,95,"{\"result\":\"fail_5\"}");
//		printf("qReturnpre5:%s\n",qReturnpre);
		websEncode64(qReturn,qReturnpre,95);
		websWrite(wp, T("%s\n"),qReturn);
		websDone(wp, 200);
		bfree(B_L,strbuf);
		bfree(B_L,qReturnpre);
		bfree(B_L,qReturn);
		bfree(B_L,base64de);
		bfree(B_L,staffnum);
		bfree(B_L,staffname);
		bfree(B_L,staffdp);
		bfree(B_L,off_type);
		return;
	} 
	oindex2=strchr(oindex1+12,'"');
    char_t* off_from = "\0";	
	off_from = balloc(B_L,64);
	strcpy(strbuf,"\0");
	strncpy(strbuf,oindex1+12,oindex2-(oindex1+12));
	strcpy(strbuf+(oindex2-(oindex1+12)),"\0");
	websDecode64(off_from,strbuf,64);
//	printf("off_from:%s\n",off_from);
	oindex1=strstr(base64de,"\"off_to\":\"");
	if(oindex1==NULL)
    {
	    snprintf(qReturnpre,95,"{\"result\":\"fail_5\"}");
//		printf("qReturnpre6:%s\n",qReturnpre);
		websEncode64(qReturn,qReturnpre,95);
		websWrite(wp, T("%s\n"),qReturn);
		websDone(wp, 200);
		bfree(B_L,strbuf);
		bfree(B_L,qReturnpre);
		bfree(B_L,qReturn);
		bfree(B_L,base64de);
		bfree(B_L,staffnum);
		bfree(B_L,staffname);
		bfree(B_L,staffdp);
		bfree(B_L,off_type);
		bfree(B_L,off_from);
		return;
	} 
	oindex2=strchr(oindex1+10,'"');
    char_t* off_to = "\0";	
	off_to = balloc(B_L,64);
	strcpy(strbuf,"\0");
	strncpy(strbuf,oindex1+10,oindex2-(oindex1+10));
	strcpy(strbuf+(oindex2-(oindex1+10)),"\0");
	websDecode64(off_to,strbuf,64);
//	printf("off_to:%s\n",off_to);
//	oindex1=strstr(base64de,"\"off_note\":\"");
//	if(oindex1==NULL)
//    {
//	    snprintf(qReturnpre,95,"{\"result\":\"fail_5\"}");
//		printf("qReturnpre7:%s\n",qReturnpre);
//		websEncode64(qReturn,qReturnpre,95);
//		websWrite(wp, T("%s\n"),qReturn);
//		websDone(wp, 200);
//		bfree(B_L,strbuf);
//		bfree(B_L,qReturnpre);
//		bfree(B_L,qReturn);
//		bfree(B_L,base64de);
//		bfree(B_L,staffnum);
//		bfree(B_L,staffname);
//		bfree(B_L,staffdp);
//		bfree(B_L,off_type);
//		bfree(B_L,off_from);
//		bfree(B_L,off_to);
//		return;
//	} 
//	oindex2=strchr(oindex1+12,'"');
    char_t* off_note = "null";	
//	off_note = balloc(B_L,64);
//	strncpy(strbuf,oindex1+12,oindex2-(oindex1+12));
//	strcpy(strbuf+(oindex2-(oindex1+12)),"\0");
//	printf("off_note1:%s\n",strbuf);
//	websDecode64(off_note,strbuf,64);
//	printf("off_note:%s\n",off_note);
//	printf("staffnum:%s,staffname:%s,staffdp:%s,off_type:%s,off_from:%s,off_to:%s,off_note:%s\n",staffnum,staffname,
//	    staffdp,off_type,off_from,off_to,off_note);
	if((!staffnum)||!(*staffnum)||(!staffname)||!(*staffname)||(!staffdp)||!(*staffdp)||(!off_type)||!(*off_type)
	    ||(!off_from)||!(*off_from)||(!off_to)||!(*off_to)||strlen(off_type)>18||strlen(off_from)>21||
		strlen(off_to)>21||strlen(off_note)>28)
	{		
        snprintf(qReturnpre,95,"{\"result\":\"fail_1\"}");
//		printf("qReturnpre:%s\n",qReturnpre);
		websEncode64(qReturn,qReturnpre,95);
		websWrite(wp, T("%s\n"),qReturn);
		websDone(wp, 200);
	}else
	{
	    char_t* sqlstr;
	    sqlstr = balloc(B_L,256);
		int ncols=0,nrows=0;
	    int rc = 0;
        unsigned char* staffnumbuff[1];
	    staffnumbuff[0] = balloc(B_L,33);
		rc = snprintf(sqlstr,255,"insert into attendanceoff(staffnum,staffname,departmentname,typeofoff,\
		    startofoff,endofoff,noteofoff) values('%s','%s','%s','%s','%s','%s','%s');",staffnum,staffname,
			staffdp,off_type,off_from,off_to,off_note);
        rc = dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows);
		bfree(B_L,staffnumbuff[0]);
		bfree(B_L,sqlstr);
//		printf("%s\n",sqlstr);		
	    if(rc<0)
        {
    		snprintf(qReturnpre,95,"{\"result\":\"fail_2\"}");
//		    printf("qReturnpre:%s\n",qReturnpre);
		    websEncode64(qReturn,qReturnpre,95);
			websWrite(wp, T("%s\n"),qReturn);
		    websDone(wp, 200);
		}else
		{
		    snprintf(qReturnpre,95,"{\"result\":\"complete\"}");
//    	    printf("qReturnpre:%s\n",qReturnpre);
		    websEncode64(qReturn,qReturnpre,95);
			websWrite(wp, T("%s\n"),qReturn);
		    websDone(wp, 200);
		}
	}
	bfree(B_L,strbuf);
	bfree(B_L,qReturnpre);
	bfree(B_L,qReturn);
	bfree(B_L,base64de);
	bfree(B_L,staffnum);
	bfree(B_L,staffname);
	bfree(B_L,staffdp);
	bfree(B_L,off_type);
	bfree(B_L,off_from);
	bfree(B_L,off_to);
//	bfree(B_L,off_note);
}

static void dwDeloff(webs_t wp, char_t *path, char_t *query)
{
    websText(wp);
//	printf("%s\n",query);	
	if(!query || (!strlen(query)))
	{
	    websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
	char_t* rtl;
    rtl = balloc(B_L,33);
	int ncols=0,nrows=0;
	if(dwreadwriteDB(query,(unsigned char**)&rtl,&ncols,&nrows)<0) 
	{
//	    printf("dwDeloff delete err.\n");
	    websWrite(wp, T("%s"),"dwDeloff err.");
	}else
	{
//	    websHeader(wp);
//        websWrite(wp, T("%s"),"200");		
    }
	websDone(wp, 200);
	bfree(B_L,rtl);
}

static void dwreadstatistics(webs_t wp, char_t *path, char_t *query)
{   	
	if(!query || (!strlen(query)))
	{
	    websText(wp);
		websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
	char_t* strbuf;
	strbuf = balloc(B_L,256);
	strcpy(strbuf,query);
//	printf("strbuf:%s\n",strbuf);
	char_t* sIndex1=NULL;
	char_t* sIndex2=NULL;
	char_t* h0;
	h0 = balloc(B_L,24);
    if(strstr(strbuf,"h0"))
	{
	    sIndex1=strstr(strbuf,"\"h0\":\"")+6;
//		printf("strbuf3:%s\n",sIndex1);
        strncpy(h0,sIndex1,23);
//		printf("strbuf4:%s\n",h0);
        sIndex2=strchr(h0,'"');
        *(sIndex2)='\0';
//        printf("h0:%s \n",h0);		
	}
	char_t* h1;
	h1 = balloc(B_L,24);
    if(strstr(strbuf,"h1"))
	{
	    sIndex1=strstr(strbuf,"\"h1\":\"")+6;
//		printf("strbuf5:%s\n",sIndex1);
        strncpy(h1,sIndex1,23);
//		printf("strbuf6:%s\n",h1);
        sIndex2=strchr(h1,'"');
        *(sIndex2)='\0';
//        printf("h1:%s \n",h1);		
	}
	if(strncmp(h0,h1,20)>=0)
	{
		websText(wp);
		websWrite(wp, T("%s"),"<script language=\"JavaScript\">alert(\"结束日期小于开始日期，请重新输入。\");</script><br/>");
	    websDone(wp, 200);
		bfree(B_L,strbuf);
	    bfree(B_L,h0);
	    bfree(B_L,h1);
		return;
	}
	//get end
	char_t* rowsnum;
	rowsnum = balloc(B_L,24);
    char_t* sqlstr;
	sqlstr = balloc(B_L,1024);
	char rc; 
    sqlite3 *connstac = NULL;	
	rc = sqlite3_open("/mnt/user/dwdoor.db",&connstac);	
	if (rc != SQLITE_OK) 
	{
        sqlite3_close(connstac);
//        printf("dwreadDBstac_open_err.\n");
//        sprintf(content,"dwreadDB_open_err.\n");
//        dwwrite(content);
		return;
    }
	
    int d,e=369;   			
	for(d=0;d<=369;d++)
	{
	    snprintf(sqlstr,255,"select strftime('%%Y-%%m-%%d','%s','+%d day')",h0,d);
        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select0 err.\n");		
		if(!strncmp(rowsnum,h1,10))
		{
		    e=d;
			break;
		}
		if(d>368)
		{
			websText(wp);
			websWrite(wp, T("%s"),"<script language=\"JavaScript\">alert(\"超范围，日期多于365天，请重新输入。\");</script><br/>");
			websDone(wp, 200);
		    bfree(B_L,strbuf);
	        bfree(B_L,h0);
	        bfree(B_L,h1);
			bfree(B_L,sqlstr);
	        bfree(B_L,rowsnum);
			sqlite3_close(connstac);
		    return; 
		}
	}	
//	printf("e:%d\n",e);
	static unsigned char i,j;  
	char_t* s;
	s = balloc(B_L,256);	
	char_t* staffbasesettingtab;
	staffbasesettingtab = balloc(B_L,2640);
	strcpy(staffbasesettingtab,"{\0");
	char_t* dbResult[112];
	for(i=0;i<112;i++)
	{
	    dbResult[i] = balloc(B_L,18);	
	}
	strcpy(sqlstr,"select COUNT(*) from staffbasesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select1 err.\n");
//	printf("rowsnum=%s\n",rowsnum);
	int pagemax=1;
	pagemax = (((gatoi(rowsnum))/10.0)-(int)((gatoi(rowsnum))/10.0))>0.?(int)((gatoi(rowsnum))/10.0)+1
	    :(int)((gatoi(rowsnum))/10.0);	
	char formpagenum=1;
	int pagestart=1;
	int pageend=1;
	char_t* pagei;
	pagei = balloc(B_L,24);
    if(strstr(strbuf,"pagei"))
	{
	    sIndex1=strstr(strbuf,"\"pagei\":\"")+9;
//		printf("strbuf1:%s\n",sIndex1);
        strncpy(pagei,sIndex1,23);
//		printf("strbuf2:%s\n",pagei);
        sIndex2=strchr(pagei,'"');
        *(sIndex2)='\0';
//        printf("pagei:%s \n",pagei);		
	}
	formpagenum=gatoi(pagei);
	if(formpagenum>pagemax) formpagenum=pagemax;
	pagestart=10*formpagenum-10;
    pageend=10;	
//	printf("formpagenum:%d pagestart:%d pageend:%d\n",formpagenum,pagestart,pageend);
//	printf("pagemax=%d\n",pagemax);
	snprintf(sqlstr,255,"select rowid,staffnum,staffname,departmentname from staffbasesetting limit %d,%d;",
	    pagestart,pageend);	
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&dbResult,connstac)<0) printf("dwreadstatistics select2 err.\n");
//	int snrows,sncols;
//	snrows=nrows;
//	sncols=ncols;	
	snprintf(sqlstr,255,"select swipecardnum from attendancesetting;");	
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select3 err.\n");
	int swipecardnum = gatoi(rowsnum);
//    printf("snrows=%d,sncols=%d swipecardnum=%d\n",snrows,sncols,swipecardnum);
	if(swipecardnum==2)
	{
        snprintf(sqlstr,1023,"DROP TABLE attendanceform;");
        rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);
        if(rc<0) printf("dwreadstatistics select331 err.\n");		
		snprintf(sqlstr,1023,"create table if not exists attendanceform(skid text,staffnum text,staffname text,\
			departmentname text,latetimes text,earlytimes text,overtimes text,absentofwork text,offtimes text);");
		rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);
		if(rc<0) printf("dwreadstatistics select332 err.\n");
	}else if(swipecardnum==4)
    {
	    snprintf(sqlstr,1023,"DROP TABLE attendanceform;");
        rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);
		if(rc<0) printf("dwreadstatistics select333 err.\n");
		snprintf(sqlstr,1023,"create table if not exists attendanceform(skid text,staffnum text,staffname text,\
		    departmentname text,latetimes text,earlytimes text,amearlytimes text,pmlatetimes text,\
			overtimes text,absentofwork text,offtimes text);");
		rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);
        if(rc<0) printf("dwreadstatistics select334 err.\n");		
	}
	//prepare absentofwork.
	float absentofwork=0.0;
	int tolerateoflate;
	float absentofworkaslate;
	snprintf(sqlstr,255,"select tolerateoflate from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select4 err.\n");
	tolerateoflate=gatoi(rowsnum);
	snprintf(sqlstr,255,"select absentofworkaslate from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select5 err.\n");
	absentofworkaslate=atof(rowsnum);
	int tolerateofearly;
	float absentofworkasearly=0.0;
	snprintf(sqlstr,255,"select tolerateofearly from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select6 err.\n");
	tolerateofearly=gatoi(rowsnum);
	snprintf(sqlstr,255,"select absentofworkasearly from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select7 err.\n");
	absentofworkasearly=atof(rowsnum);
	char_t* workstart;
	workstart=balloc(B_L,16);	
	snprintf(sqlstr,255,"select workstart from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select8 err.\n");
	strncpy(workstart,rowsnum,8);
	char_t* workoff;
	workoff=balloc(B_L,16);	
	snprintf(sqlstr,255,"select workoff from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select9 err.\n");
	strncpy(workoff,rowsnum,8);
	char_t* morningworkoff;
	morningworkoff=balloc(B_L,16);	
	snprintf(sqlstr,255,"select morningworkoff from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select10 err.\n");
	strncpy(morningworkoff,rowsnum,8);
	char_t* afternoonworkstart;
	afternoonworkstart=balloc(B_L,16);	
	snprintf(sqlstr,255,"select afternoonworkstart from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select11 err.\n");
	strncpy(afternoonworkstart,rowsnum,8);

	int absentamearlytimes=0,absentpmlatetimes=0,pmlatetimes=0,amearlytimes=0;
	int allabsent=1,amabsent=1,pmabsent=1,middleattendance=0;
	
	//prepare late times.
	int latetimes=0,absentlatetimes=1;
	int earlytimes=0,absentearlytimes=1;
	snprintf(sqlstr,255,"select extenoflate from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select12 err.\n");
	int extenoflate=atof(rowsnum);
	snprintf(sqlstr,255,"select extenofearly from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select13 err.\n");
	int extenofearly=atof(rowsnum);
//	printf("extenoflate:%d extenofearly:%d\n",extenoflate,extenofearly);
    
	//prepare overtime.	
	snprintf(sqlstr,255,"select overtimeafter from attendancesetting;");
	if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select14 err.\n");
	int overtimeafter=atof(rowsnum);
	float overtimes=0.00;
	int atValue=0;                     //attendance state,0:should be all day;1: AM should be;2:PM should be;3:not be. 
	
	for(i=1;i<=snrows;i++)
	{
	    //get off times;
		snprintf(sqlstr,255,"select COUNT(*) from attendanceoff where staffnum='%s' and staffname='%s' and startofoff<='%s' \
		    and endofoff>='%s';",*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h1,h0);
        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select15 err.\n");       			
		int offtimes=gatoi(rowsnum);  
//        printf("offtimes=%d\n",offtimes);	        		
		        	
		for(d=0;d<=e;d++)
		{		    
			//get attendance day;	
			//is holiday?
			if(d==0 && d==e)
			{
			    snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where '%s'<= holidayto and '%s'>=holidayfrom and \
					strftime('%%H:%%M:%%S',holidayto)>'12:00:00' and strftime('%%H:%%M:%%S',holidayfrom)<'12:00:00';",h0,h1);
		        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select16 err.\n");
//		        printf("d0+de holiday:%s\n",rowsnum);
			    if(gatoi(rowsnum)!=0)
			    {
			  	    atValue=3;
                }else
 				{
				    snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where '%s'<= holidayto and '%s'>=holidayfrom and \
					   strftime('%%H:%%M:%%S',holidayto)<'12:00:00';",h0,h1);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select17 err.\n");   
					if(gatoi(rowsnum)!=0)
			        {
					    atValue=1;
					}else
					{
					    snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where '%s'<= holidayto and '%s'>=holidayfrom and \
					        strftime('%%H:%%M:%%S',holidayfrom)>'12:00:00';",h0,h1);
					    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select18 err.\n");   
					    if(gatoi(rowsnum)!=0)
			            {
						    atValue=2;   
					    }
				    }
			    }
//			printf("d0+de atValue:%d\n",atValue);
			}else if(d==0)
			{
                snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where '%s'<= holidayto and strftime('%%Y-%%m-%%d %%H:%%M:%%S',\
				    '%s','start of day','+18.5 hour','-%d minute')>=holidayfrom and strftime('%%H:%%M:%%S',holidayto)>'12:00:00' and \
					strftime('%%H:%%M:%%S',holidayfrom)<='12:00:00';",h0,h0,tolerateofearly);
		        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select19 err.\n");
//		        printf("d0 holiday:%s\n",rowsnum);
			    if(gatoi(rowsnum)!=0) 
			    {
			        atValue=3; 
				}else
				{
					snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where '%s'<= holidayto and \
					    strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+18.5 hour','-%d minute')>=\
						holidayfrom and strftime('%%H:%%M:%%S',holidayto)<'12:00:00';",h0,h0,tolerateofearly);
                    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select20 err.\n");
					if(gatoi(rowsnum)!=0)
					{
					    atValue=1;
                    }else
 					{
					    snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where '%s'<= holidayto and \
						    strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+18.5 hour','-%d minute')>=\
							holidayfrom and strftime('%%H:%%M:%%S',holidayfrom)>'12:00:00';",h0,h0,tolerateofearly);
                        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select21 err.\n");
					    if(gatoi(rowsnum)!=0)
					    {
					        atValue=2;
						}
					}
			    }
//			    printf("d0 atValue:%d\n",atValue); 	
			}else if(d==e)
			{
			    snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where strftime('%%Y-%%m-%%d \
				    %%H:%%M:%%S','%s','start of day')<=holidayto and '%s'>=holidayfrom and strftime('%%H:%%M:%%S'\
					,holidayto)>='12:00:00' and strftime('%%H:%%M:%%S',holidayfrom)<='12:00:00';",h1,h1);
		        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select22 err.\n");
//		        printf("de holiday:%s\n",rowsnum);
			    if(gatoi(rowsnum)!=0)
			    {
			        atValue=3;
				}else
				{
     				snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where strftime('%%Y-%%m-%%d \
					    %%H:%%M:%%S','%s','start of day')<=holidayto and '%s'>=holidayfrom and \
						strftime('%%H:%%M:%%S',holidayto)<'12:00:00';",h1,h1);
                    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select22 err.\n");
					if(gatoi(rowsnum)!=0)
					{
					    atValue=1;
                    }else
 					{
					    snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where strftime('%%Y-%%m-%%d \
						    %%H:%%M:%%S','%s','start of day')<=holidayto and '%s'>=holidayfrom and \
							strftime('%%H:%%M:%%S',holidayfrom)>'12:00:00';",h1,h1);
                        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select23 err.\n");
					    if(gatoi(rowsnum)!=0)
					    {
					        atValue=2;
						}
					} 
			    }
//				printf("de atValue:%d\n",atValue);
			}else
			{
			    snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where strftime('%%Y-%%m-%%d \
				    %%H:%%M:%%S','%s','start of day','+%d day')<=holidayto and strftime('%%Y-%%m-%%d %%H:%%M:%%S',\
					'%s','start of day','+23 hour','+59 minute','+59 second','+%d day')>=holidayfrom \
					and strftime('%%H:%%M:%%S',holidayto)>'12:00:00' and strftime('%%H:%%M:%%S',holidayfrom)<\
					'12:00:00';",h0,d,h0,d);
		        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select24 err.\n");
//		        printf("holiday:%s\n",rowsnum);
			    if(gatoi(rowsnum)!=0)
			    {
				    atValue=3;
                }else
 				{
				    snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where strftime('%%Y-%%m-%%d \
				        %%H:%%M:%%S','%s','start of day','+%d day')<=holidayto and strftime('%%Y-%%m-%%d %%H:%%M:%%S',\
					    '%s','start of day','+23 hour','+59 minute','+59 second','+%d day')>=holidayfrom \
						and strftime('%%H:%%M:%%S',holidayto)<'12:00:00';",h0,d,h0,d);
                    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select25 err.\n");
					if(gatoi(rowsnum)!=0)
					{
					    atValue=1;
					}else
					{
						snprintf(sqlstr,511,"select COUNT(*) from attendanceholiday where strftime('%%Y-%%m-%%d \
				        %%H:%%M:%%S','%s','start of day','+%d day')<=holidayto and strftime('%%Y-%%m-%%d %%H:%%M:%%S',\
					    '%s','start of day','+23 hour','+59 minute','+59 second','+%d day')>=holidayfrom and \
						strftime('%%H:%%M:%%S',holidayfrom)>'12:00:00';",h0,d,h0,d);
                        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select26 err.\n");
					    if(gatoi(rowsnum)!=0) 
						{
     						atValue=2;   
					    }
				    } 
		        }
//			    printf("holiday atValue:%d\n",atValue);
			}
			
			//is off?
			if(atValue==3)
			{
			}else
			{
		        if(d==0 && d==e)
			    {
				    snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND staffname='%s'\
    					AND '%s'<= endofoff and '%s'>=startofoff and strftime('%%H:%%M:%%S',endofoff)>='12:00:00'\
						and strftime('%%H:%%M:%%S',startofoff)<='12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,h1);
		            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select27 err.\n");
		            printf("d0+de off:%s\n",rowsnum);
			        if(gatoi(rowsnum))
			        {
			            atValue=3; 
			        }else
					{
					    snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND staffname\
						    ='%s' AND '%s'<= endofoff and '%s'>=startofoff and strftime('%%H:%%M:%%S',endofoff)<\
							'12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,h1);
		                if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select28 err.\n");
					    if(gatoi(rowsnum) && atValue==2)
			            {
			                atValue=3; 
			            }else if(gatoi(rowsnum)!=0)
						{
						    atValue=1;
						}else
					    {
						    snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND \
							    staffname='%s' AND '%s'<= endofoff and '%s'>=startofoff and strftime('%%H:%%M:%%S'\
								,startofoff)>'12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),\
								*(dbResult+((i-1)*sncols)+(3-1)),h0,h1);
		                    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select29 err.\n");
					        if(gatoi(rowsnum)!=0 && atValue==1)
						    {
							    atValue=3;
							}else if(gatoi(rowsnum)!=0)
							{
							    atValue=2;
							}
						}
					}
				}else if(d==0)
			    {
				    snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND staffname='%s'\
    					AND '%s'<= endofoff and strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+23 hour',\
						'+59 minute','+59 second')>=startofoff and strftime('%%H:%%M:%%S',endofoff)>='12:00:00'\
						and strftime('%%H:%%M:%%S',startofoff)<='12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),\
						*(dbResult+((i-1)*sncols)+(3-1)),h0,h0);
		            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select30 err.\n");
		            printf("d0 off:%s\n",rowsnum);
			        if(gatoi(rowsnum)!=0)
   		            {
			            atValue=3; 
			        }else
					{ 
				        snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND staffname\
						    ='%s' AND '%s'<= endofoff and strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day',\
							'+23 hour','+59 minute','+59 second')>=startofoff and strftime('%%H:%%M:%%S',endofoff)\
							<'12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,h0);
		                if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select31 err.\n");
				        if(gatoi(rowsnum)!=0&&atValue==2)
			            {
			                atValue=3; 
			            }else if(gatoi(rowsnum)!=0)
						{
						    atValue=1;
						}else
					    {
					        snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND\
    							staffname='%s' AND '%s'<= endofoff and strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s',\
								'start of day','+23 hour','+59 minute','+59 second')>=startofoff and\
								strftime('%%H:%%M:%%S',startofoff)>'12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),
								*(dbResult+((i-1)*sncols)+(3-1)),h0,h0);
		                    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select32 err.\n");
					    }
					    if(gatoi(rowsnum)!=0&&atValue==1)
			            {
			                atValue=3; 
			            }else if(gatoi(rowsnum)!=0)
                        {
						    atValue=2;
						}						
				    }
				}else if(d==e)
			    {
                    snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND\
    					staffname='%s' AND strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+%d day')\
						<=endofoff and '%s'>=startofoff and strftime('%%H:%%M:%%S',endofoff)>='12:00:00' and\
						strftime('%%H:%%M:%%S',startofoff)<='12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,h1);
                    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select33 err.\n");
//					printf("de off:%s\n",rowsnum);
					if(gatoi(rowsnum)!=0)
			        {
			            atValue=3; 
			        }else
                    {
				        snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND\
    					    staffname='%s' AND strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+%d day')\
							<=endofoff and '%s'>=startofoff and strftime('%%H:%%M:%%S',endofoff)<'12:00:00';",
							*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,d,h1);
                        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select34 err.\n"); 
				    	if(gatoi(rowsnum)!=0 && atValue==2)
			            {
			                atValue=3; 
			            }else if(gatoi(rowsnum)!=0)
						{
						    atValue=1;						
						}else
                        {
					        snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND\
    					        staffname='%s' AND strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day',\
								'+%d day')<=endofoff and '%s'>=startofoff and strftime('%%H:%%M:%%S',startofoff)\
								>'12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),
								h0,d,h1);
                            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select35 err.\n");
						    if(gatoi(rowsnum)!=0 && atValue==1)
			                {
			                    atValue=3;  
					        }else if(gatoi(rowsnum)!=0)
                            {
							    atValue=2;
							}							
                        }
                    }				
			    }else
				{
				    snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND\
    					staffname='%s' AND strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+%d day')\
						<=endofoff and strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+24 hour',\
						'+%d day')>=startofoff and strftime('%%H:%%M:%%S',endofoff)>='12:00:00' and\
						strftime('%%H:%%M:%%S',startofoff)<='12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,h0,d);
		            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select36 err.\n");
//		    	    printf("off:%s\n",rowsnum);
					if(gatoi(rowsnum)!=0)
			        {
			            atValue=3; 
			        }else
                    {
			            snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND\
    					    staffname='%s' AND strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+%d day')\
							<=endofoff and strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+24 hour',\
							'+%d day')>=startofoff and strftime('%%H:%%M:%%S',endofoff)<'12:00:00';",
							*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,d,h0,d);
		                if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select37 err.\n");
				        if(gatoi(rowsnum)!=0 && atValue==2)
			            {
			                atValue=3; 
			   		    }else if(gatoi(rowsnum)!=0)
						{
						    atValue=1;
						}else
			   			{
			   			    snprintf(sqlstr,640,"select COUNT(*) from attendanceoff where staffnum='%s' AND\
    					        staffname='%s' AND strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day',\
								'+%d day')<=endofoff and strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day',\
								'+24 hour','+%d day')>=startofoff and strftime('%%H:%%M:%%S',startofoff)>\
								'12:00:00';",*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),
								h0,d,h0,d);
		                    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select38 err.\n");
				            if(gatoi(rowsnum)!=0 && atValue==1)
			                {
			                    atValue=3; 
				            }else if(gatoi(rowsnum)!=0)
							{
							    atValue=2;							
							}							
					    }	
					}
				}
//				printf("off atValue:%d\n",atValue);
			}			
			
			//is rest?
			if(atValue==3)
			{
			}else
			{
			    snprintf(sqlstr,255,"select strftime('%%w','%s','+%d day');",h0,d);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select39 err.\n");
//		        printf("week:%s\n",rowsnum);
			    int w=gatoi(rowsnum);
			    if(w==6)                                 //saturday
			    {    
			        snprintf(sqlstr,255,"select saturdayrest from attendancesetting;");
                    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select40 err.\n");
                    if(gatoi(rowsnum)==1)
                    {
                        atValue=3;				
				    }else
                    {
				        snprintf(sqlstr,255,"select saturdayamwork from attendancesetting;");
                        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select41 err.\n");
					    if(gatoi(rowsnum)==1 && atValue==2)
                        {
				            atValue=3; 
				        }else if(gatoi(rowsnum)==1)
                        {
					        atValue=1;
						}else
						{
						    snprintf(sqlstr,255,"select saturdaypmwork from attendancesetting;");
                            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select42 err.\n");
					        if(gatoi(rowsnum)==1 && atValue==1)
                            {				            
				                atValue=3;
						    }else if(gatoi(rowsnum)==1)
                            {
							    atValue=2;
							}
						}	
					}
				}else if(w==0)                            //sunday      
			    {
			        snprintf(sqlstr,255,"select sundayrest from attendancesetting;");
                    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select43 err.\n");
                    if(gatoi(rowsnum)==1)
                    {
				        atValue=3;
				    }else
                    {
				        snprintf(sqlstr,255,"select sundayamwork from attendancesetting;");
                        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select44 err.\n");
					    if(gatoi(rowsnum)==1 && atValue==2)
                        {
				            atValue=3;
				        }else if(gatoi(rowsnum)==1)
					    {
					        atValue=1;
					    }else
                        {
					        snprintf(sqlstr,255,"select sundaypmwork from attendancesetting;");
                            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select45 err.\n");
					        if(gatoi(rowsnum)==1 && atValue==1)
                            { 
				               atValue=3;    
				            }else if(gatoi(rowsnum)==1)
                            {
					           atValue=2;
						    }	
					    }
				    }			
			    }
//				printf("rest atValue:%d\n",atValue);
		    }
           
    	    //forcework
            if(atValue==0)
			{
			}else
			{
			    if(d==0 && d==e)
				{
				    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where '%s' <=forceto and '%s'>=forcefrom and \
					    strftime('%%H:%%M:%%S',forcefrom)<'12:00:00' AND strftime('%%H:%%M:%%S',forceto)>'12:00:00';",h0,h1);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select46 err.\n");
					if(gatoi(rowsnum))
					{
					    atValue=0;
					}else
					{
					    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where '%s' <=forceto and '%s'>=forcefrom and\
     						strftime('%%H:%%M:%%S',forceto)<'12:00:00';",h0,h1);
					    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select47 err.\n");
					    if(gatoi(rowsnum))
					    {
					        if(atValue==2)
							{
							    atValue=0;
							}else
							{
						    	atValue=1;
							}
					    }else
						{
						    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where '%s' <=forceto and\
    							'%s'>=forcefrom and strftime('%%H:%%M:%%S',forcefrom)>'12:00:00';",h0,h1);
					        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select48 err.\n");
					        if(gatoi(rowsnum))
					        {
					            if(atValue==1)
								{
								   atValue=0; 
								}else
								{
								   atValue=2;
					            } 
							}
                        } 						
					}
                }else if(d==0)
				{
				    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where '%s'<=forceto and\
    					strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+23 hour','+59 minute',\
						'+59 second')>=forcefrom and strftime('%%H:%%M:%%S',forcefrom)<'12:00:00' AND\
						strftime('%%H:%%M:%%S',forceto)>'12:00:00';",h0,h0);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select49 err.\n");
					if(gatoi(rowsnum))
					{
					    atValue=0;
					}else
					{
					    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where '%s'<=forceto and\
    					    strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+23 hour','+59 minute',\
					    	'+59 second')>=forcefrom and strftime('%%H:%%M:%%S',forceto)<'12:00:00';",h0,h0);
					    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select50 err.\n");
					    if(gatoi(rowsnum))
					    {
					        if(atValue==2)
							{
							    atValue=0;
							}else
							{
						    	atValue=1;
							}
					    }else
						{ 
						    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where '%s'<=forceto and\
    					        strftime('%%Y-%%m-%%d %%H:%%M:%%S','%s','start of day','+23 hour','+59 minute',\
					    	    '+59 second')>=forcefrom and strftime('%%H:%%M:%%S',forcefrom)>'12:00:00';",h0,h1);
					        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select51 err.\n");
					        if(gatoi(rowsnum))
					        {
					            if(atValue==1)
								{
								   atValue=0; 
								}else
								{
								   atValue=2;
					            } 
					        }
                        }						
					}
                }else if(d==e)
				{
				    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where strftime('%%Y-%%m-%%d\
    					%%H:%%M:%%S','%s','start of day')<=forceto and '%s'>=forcefrom and strftime('%%H:%%M:%%S',\
						forcefrom)<'12:00:00' AND strftime('%%H:%%M:%%S',forceto)>'12:00:00';",h1,h1);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select52 err.\n");
					if(gatoi(rowsnum))
					{
					    atValue=0;
					}else
					{
					    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where strftime('%%Y-%%m-%%d\
    					    %%H:%%M:%%S','%s','start of day')<=forceto and '%s'>=forcefrom and strftime('%%H:%%M:%%S',\
							forceto)<'12:00:00';",h1,h1);
					    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select53 err.\n");
					    if(gatoi(rowsnum))
					    {
					        if(atValue==2)
							{
							    atValue=0;
							}else
							{
						    	atValue=1;
							}
					    }else
                        { 						
						    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where strftime('%%Y-%%m-%%d\
    					        %%H:%%M:%%S','%s','start of day')<=forceto and '%s'>=forcefrom and \
								strftime('%%H:%%M:%%S',forcefrom)>'12:00:00';",h0,h1);
					        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select54 err.\n");
					        if(gatoi(rowsnum))
					        {
					            if(atValue==1)
								{
								   atValue=0; 
								}else
								{
								   atValue=2;
					            } 
					        }
						}
                    }						
				}else
				{
				    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where strftime('%%Y-%%m-%%d\
    					%%H:%%M:%%S','%s','start of day','+%d day')<=forceto and strftime('%%Y-%%m-%%d\
    					%%H:%%M:%%S','%s','start of day','+23 hour','+59 minute','+59 second','+%d day')>=\
						forcefrom and strftime('%%H:%%M:%%S',forcefrom)<'12:00:00' AND strftime('%%H:%%M:%%S',\
						forceto)>'12:00:00';",h0,d,h0,d);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select55 err.\n");
					if(gatoi(rowsnum))
					{
					    atValue=0;
					}else
					{
					    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where strftime('%%Y-%%m-%%d\
    					    %%H:%%M:%%S','%s','start of day','+%d day')<=forceto and strftime('%%Y-%%m-%%d\
    					    %%H:%%M:%%S','%s','start of day','+23 hour','+59 minute','+59 second','+%d day')>=\
						    forcefrom and strftime('%%H:%%M:%%S',forceto)<'12:00:00';",h0,d,h0,d);
					    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select56 err.\n");
					    if(gatoi(rowsnum))
					    {
					        if(atValue==2)
							{
							    atValue=0;
							}else
							{
						    	atValue=1;
							}
					    }else
                        { 						
						    snprintf(sqlstr,640,"select COUNT(*) from attendanceforce where strftime('%%Y-%%m-%%d\
    					        %%H:%%M:%%S','%s','start of day','+%d day')<=forceto and strftime('%%Y-%%m-%%d\
    					        %%H:%%M:%%S','%s','start of day','+23 hour','+59 minute','+59 second','+%d day')>=\
						        forcefrom and strftime('%%H:%%M:%%S',forcefrom)>'12:00:00';",h0,d,h0,d);
					        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select57 err.\n");
					        if(gatoi(rowsnum))
					        {
					            if(atValue==1)
								{
								   atValue=0; 
								}else
								{
								   atValue=2;
					            } 
					        }
						}
                    }	
				}
//				printf("force atValue:%d\n",atValue);
            }			
			
			//absentofwork days.
			if(!d && d==e && atValue!=3)
			{
			    if(!atValue)
				{
				    snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
					    strftime('%%H:%%M:%%S','%s','+%d minute') AND strftime('%%H:%%M:%%S','%s')>=\
						strftime('%%H:%%M:%%S','%s','-%d minute');",h0,workstart,tolerateoflate,h1,workoff,
						tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select58 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes' AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						    strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
							strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,workstart,tolerateoflate,workoff,tolerateofearly);
				        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select59 err.\n");	
					    allabsent=gatoi(rowsnum);
						if(!allabsent)
					    {
						    absentofwork += 1; 						
						}					
					}
				}
				if((allabsent && !atValue) || (swipecardnum==2 && atValue==1))
			    {
			        snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute') AND strftime('%%H:%%M:%%S','%s')>\
						strftime('%%H:%%M:%%S','%s','+%d minute');",h0,workstart,tolerateoflate,h1,workstart,
						tolerateoflate);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select60 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else  
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
				            strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						    *(dbResult+((i-1)*sncols)+(3-1)),h0,workstart,tolerateoflate);   
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select61 err.\n");
				        absentlatetimes=gatoi(rowsnum);
                        if(!absentlatetimes)
				        {
				            absentofwork += absentofworkaslate;
				        }						
 	                }			
			    }else if((allabsent && !atValue)||(swipecardnum==4 && atValue==2))
			    {
				    snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute') AND strftime('%%H:%%M:%%S','%s')>=\
						strftime('%%H:%%M:%%S','%s','-%d minute');",h0,afternoonworkstart,tolerateoflate,
						h1,workoff,tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select62 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						    strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
						    strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						    *(dbResult+((i-1)*sncols)+(3-1)),h0,afternoonworkstart,tolerateoflate,workoff,
						    tolerateofearly);
						if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select63 err.\n");	
					    pmabsent=gatoi(rowsnum);
						if(!pmabsent)
						{
						    absentofwork += 0.5; 	
						}
					}
					snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",h0,afternoonworkstart,tolerateoflate);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select64 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)<=\
				            strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,d,afternoonworkstart,tolerateoflate);   
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select65 err.\n");
				        absentpmlatetimes=gatoi(rowsnum);
				        if(!absentpmlatetimes && pmabsent)
				        {
				            absentofwork += absentofworkaslate;
				        }
					}
			    }
//				printf("d0de absentofwork late days:%.1f allabsent:%d pmabsent:%d absentpmlatetimes:%d\n",absentofwork,allabsent,
//				    pmabsent,absentpmlatetimes);
				
				if((allabsent && !atValue) || (pmabsent && atValue==2))
			    {
			        snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				        strftime('%%H:%%M:%%S','%s','+%d minute') AND strftime('%%H:%%M:%%S','%s')>=\
						strftime('%%H:%%M:%%S','%s','-%d minute'));",h0,
						afternoonworkstart,tolerateoflate,h1,workoff,tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select66 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				            strftime('%%H:%%M:%%S','%s','-%d minute');",
				            *(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workoff,tolerateofearly);
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select67 err.\n");
				        absentearlytimes=gatoi(rowsnum);
				        if(!absentearlytimes)
				        {
				            absentofwork += absentofworkasearly;
				        }
			        }
				}
				if((allabsent && !atValue) ||(swipecardnum==4 && atValue==1))
			    {
			        snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute') AND strftime('%%H:%%M:%%S','%s')>=\
						strftime('%%H:%%M:%%S','%s','-%d minute');",h0,workstart,tolerateoflate,h1,morningworkoff,
						tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select68 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						    strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
							strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,workstart,tolerateoflate,morningworkoff,
							tolerateofearly); 
						if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select69 err.\n");
					    amabsent=gatoi(rowsnum);
						if(!amabsent)	 
						{
						    absentofwork += 0.5;
						}
					}
					snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')>=\
				        strftime('%%H:%%M:%%S','%s','-%d minute');",h1,morningworkoff,tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select70 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				            strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,d,morningworkoff,tolerateofearly);
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select71 err.\n");
				        absentamearlytimes = gatoi(rowsnum);
				        if(!absentamearlytimes && amabsent)
				        {
				            absentofwork += absentofworkasearly;
				        }
					}	
			    }
//				printf("d0de absentofwork early days:%.1f amabsent:%d absentamearlytimes:%d \n",absentofwork,
//				    amabsent,absentamearlytimes);
				if(swipecardnum==4 && !atValue && absentearlytimes && absentlatetimes && allabsent && amabsent && pmabsent)
			    {
			        snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
					    strftime('%%H:%%M:%%S','%s','-%d minute') AND strftime('%%H:%%M:%%S','%s')>=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",h0,morningworkoff,tolerateofearly,h1,
						afternoonworkstart,tolerateoflate);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select72 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from\
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck \
							from gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',\
							CreatedTime)>=strftime('%%H:%%M:%%S','%s','-%d minute') and strftime('%%H:%%M:%%S',\
							CreatedTime)<=strftime('%%H:%%M:%%S','%s','+%d minute');",
							*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,d,morningworkoff,
							tolerateofearly,afternoonworkstart,tolerateoflate);
				        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select73 err.\n");	
			            middleattendance = gatoi(rowsnum);
				        if(!middleattendance)
				        {
				            absentofwork += absentofworkasearly;
					        absentofwork += absentofworkaslate;
				        }
				        if(middleattendance==1)
				        {
				            absentofwork += absentofworkasearly;
				        }
			        }
                }
//                printf("d0de middleattendance:%d\n",middleattendance);				
			}else if(d==0 && atValue!=3)
			{
			    if(atValue==0)
				{
				    snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",h0,workstart,tolerateoflate);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select74 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						    strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
							strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,workstart,tolerateoflate,workoff,tolerateofearly);
				        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select75 err.\n");	
					    allabsent=gatoi(rowsnum);
						if(!allabsent)
					    {
						    absentofwork += 1; 						
						}					
					}
				}
				if((allabsent && !atValue) || (swipecardnum==2 && atValue==1))
			    {
			        snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",h0,workstart,tolerateoflate);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select76 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else  
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
				            strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						    *(dbResult+((i-1)*sncols)+(3-1)),h0,workstart,tolerateoflate);   
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select77 err.\n");
				        absentlatetimes=gatoi(rowsnum);
                        if(!absentlatetimes)
				        {
				            absentofwork += absentofworkaslate;
				        }						
 	                }			
			    }else if((allabsent && !atValue)||(swipecardnum==4 && atValue==2))
			    {
				    snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",h0,afternoonworkstart,tolerateoflate);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select78 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						    strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
							strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,afternoonworkstart,tolerateoflate,
						    workoff,tolerateofearly);
						if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select79 err.\n");	
					    pmabsent=gatoi(rowsnum);
						if(!pmabsent)
						{
						    absentofwork += 0.5; 	
						}else
						{
					        snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)<=\
				            strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,d,afternoonworkstart,tolerateoflate);   
			                if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select80 err.\n");
				            absentpmlatetimes=gatoi(rowsnum);
				            if(!absentpmlatetimes)
				            {
				                absentofwork += absentofworkaslate;
				            }
						}
					}
			    }
//				printf("d0 absentofwork late days:%.1f allabsent:%d pmabsent:%d absentpmlatetimes:%d\n",absentofwork,allabsent,
//				    pmabsent,absentpmlatetimes);
				
				if((allabsent && !atValue) || (pmabsent && atValue==2))
			    {
				    snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				        strftime('%%H:%%M:%%S','%s','-%d minute');",h0,workoff,tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select81 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
				            gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
				            CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',\
							CreatedTime)>=strftime('%%H:%%M:%%S','%s','-%d minute');",
							*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workoff,
							tolerateofearly);
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select82 err.\n");
				        absentearlytimes=gatoi(rowsnum);
				        if(!absentearlytimes)
				        {
				            absentofwork += absentofworkasearly;
				        }			     
				    }
				}	
				if((allabsent && !atValue)||(swipecardnum==4 && atValue==1))
			    {
			        snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",h0,workstart,tolerateoflate);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select83 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						    strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
							strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,workstart,tolerateoflate,morningworkoff,
							tolerateofearly); 
						if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select84 err.\n");
					    amabsent=gatoi(rowsnum);
						if(!amabsent)	 
						{
						    absentofwork += 0.5;
						}
					}
					snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				        strftime('%%H:%%M:%%S','%s','-%d minute');",h0,morningworkoff,tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select85 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				            strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,d,morningworkoff,tolerateofearly);
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select86 err.\n");
				        absentamearlytimes = gatoi(rowsnum);
				        if(!absentamearlytimes && amabsent)
				        {
				            absentofwork += absentofworkasearly;
				        }
					}	
			    }
//				printf("d0 absentofwork early days:%.1f amabsent:%d absentamearlytimes:%d \n",absentofwork,
//				    amabsent,absentamearlytimes);
				if(swipecardnum==4 && !atValue && absentearlytimes && absentlatetimes && allabsent && amabsent && pmabsent)
			    {
			        snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from\
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				        strftime('%%H:%%M:%%S','%s','-%d minute') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,morningworkoff,tolerateofearly,afternoonworkstart,
						tolerateoflate);
				    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select87 err.\n");	
			        int middleattendance = gatoi(rowsnum);
				    if(!middleattendance)
				    {
				        absentofwork += absentofworkasearly;
					    absentofwork += absentofworkaslate;
				    }
				    if(middleattendance==1)
				    {
				        absentofwork += absentofworkasearly;
				    }
			    }
//                printf("d0 middleattendance:%d\n",middleattendance);				
			}else if(d==e && atValue!=3)
			{
			    if(atValue==0)
				{
				    snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')>=\
						strftime('%%H:%%M:%%S','%s','-%d minute');",h1,workoff,tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select88 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						    strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
							strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workstart,tolerateoflate,workoff,tolerateofearly);
				        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select89 err.\n");	
					    allabsent=gatoi(rowsnum);
						if(!allabsent)
					    {
						    absentofwork += 1; 						
						}					
					}
				}
				if((allabsent && !atValue) || (swipecardnum==2 && atValue==1))
			    {
			        snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",h1,workstart,tolerateoflate);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select90 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else  
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
				            strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						    *(dbResult+((i-1)*sncols)+(3-1)),h1,workstart,tolerateoflate);   
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select91 err.\n");
				        absentlatetimes=gatoi(rowsnum);
                        if(!absentlatetimes)
				        {
				            absentofwork += absentofworkaslate;
				        }						
 	                }			
			    }else if((allabsent && !atValue)||(swipecardnum==4 && atValue==2))
			    {
				    snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute') AND strftime('%%H:%%M:%%S','%s')>=\
						strftime('%%H:%%M:%%S','%s','-%d minute';",h1,afternoonworkstart,tolerateoflate,h1,
						workoff,tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select92 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						    strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
							strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h1,afternoonworkstart,tolerateoflate,
						    workoff,tolerateofearly);
						if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select93 err.\n");	
					    pmabsent=gatoi(rowsnum);
						if(!pmabsent)
						{
						    absentofwork += 0.5; 	
						}
					}
					snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",h1,afternoonworkstart,tolerateoflate);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select94 err.\n");	
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)<=\
				            strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,d,afternoonworkstart,tolerateoflate);   
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select95 err.\n");
				        absentpmlatetimes=gatoi(rowsnum);
				        if(!absentpmlatetimes && pmabsent)
				        {
				            absentofwork += absentofworkaslate;
				        }
					}
			    }
//				printf("de absentofwork late days:%.1f allabsent:%d pmabsent:%d absentpmlatetimes:%d\n",absentofwork,allabsent,
//				    pmabsent,absentpmlatetimes);
				
				if((allabsent && !atValue) || (pmabsent && atValue==2))
			    {
			        snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')>=\
				        strftime('%%H:%%M:%%S','%s','-%d minute');",h1,workoff,tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select96 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				            strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workoff,tolerateofearly);
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select97 err.\n");
				        absentearlytimes=gatoi(rowsnum);
				        if(!absentearlytimes)
				        {
				            absentofwork += absentofworkasearly;
				        }
			        }
				}
				if((allabsent && !atValue)||(swipecardnum==4 && atValue==1))
			    {
			        snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
						strftime('%%H:%%M:%%S','%s','+%d minute') AND strftime('%%H:%%M:%%S','%s')>=\
						strftime('%%H:%%M:%%S','%s','-%d minute');",h1,workstart,tolerateoflate,h1,morningworkoff,
						tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select98 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						    strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
							strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,workstart,tolerateoflate,morningworkoff,
							tolerateofearly); 
						if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select99 err.\n");
					    amabsent=gatoi(rowsnum);
						if(!amabsent)	 
						{
						    absentofwork += 0.5;
						}
					}
					snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')>=\
				        strftime('%%H:%%M:%%S','%s','-%d minute');",h1,morningworkoff,tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select100 err.\n");
					if(!gatoi(rowsnum))
					{
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				            staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					        gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
							gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					        CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				            strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
							*(dbResult+((i-1)*sncols)+(3-1)),h0,d,morningworkoff,tolerateofearly);
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select101 err.\n");
				        absentamearlytimes = gatoi(rowsnum);
				        if(!absentamearlytimes && amabsent)
				        {
				            absentofwork += absentofworkasearly;
				        }
					}	
			    }
//				printf("de absentofwork early days:%.1f amabsent:%d absentamearlytimes:%d \n",absentofwork,
//				    amabsent,absentamearlytimes);
				if(swipecardnum==4 && !atValue && absentearlytimes && absentlatetimes && allabsent && amabsent && pmabsent)
			    {
			        snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				        strftime('%%H:%%M:%%S','%s','-%d minute') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,morningworkoff,tolerateofearly,afternoonworkstart,
						tolerateoflate);
				    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select102 err.\n");	
			        int middleattendance = gatoi(rowsnum);
				    if(!middleattendance)
				    {
				        absentofwork += absentofworkasearly;
					    absentofwork += absentofworkaslate;
				    }
				    if(middleattendance==1)
				    {
				        absentofwork += absentofworkasearly;
				    }
			    }
//                printf("de middleattendance:%d\n",middleattendance); 				
			}else if(atValue!=3)
			{
     			if(atValue==0)
				{
				    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
						strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workstart,tolerateoflate,workoff,tolerateofearly);
				    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select103 err.\n");	
					allabsent=gatoi(rowsnum);
					if(!allabsent)
					{
					    absentofwork += 1; 						
					}				
				}
				if((allabsent && atValue==0) || (swipecardnum==2 && atValue==1))
		    	{
			        snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)<=\
				        strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workstart,tolerateoflate);   
			        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select104 err.\n");
				    absentlatetimes=gatoi(rowsnum);
				    if(!absentlatetimes)
				    {
				        absentofwork += absentofworkaslate;
				    }				
			    }
			    if((allabsent && !atValue)||(swipecardnum==4 && atValue==2))
			    {
			        snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
						strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h1,afternoonworkstart,tolerateoflate,workoff,
						tolerateofearly);
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select105 err.\n");	
					pmabsent=gatoi(rowsnum);
					if(!pmabsent)
					{
					    absentofwork += 0.5; 	
					}
					snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)<=\
				        strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,afternoonworkstart,tolerateoflate);   
			        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select106 err.\n");
				    absentpmlatetimes=gatoi(rowsnum);
				    if(!absentpmlatetimes && pmabsent)
				    {
				        absentofwork += absentofworkaslate;
				    }
			    }
//			    printf("absentofwork late days:%.1f allabsent:%d pmabsent:%d absentpmlatetimes:%d\n",absentofwork,allabsent,
//				    pmabsent,absentpmlatetimes);
			    if((allabsent && !atValue) || (pmabsent && atValue==2))
			    {
			        snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				        strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workoff,tolerateofearly);
			        if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select107 err.\n");
				    absentearlytimes=gatoi(rowsnum);
				    if(!absentearlytimes)
				    {
				        absentofwork += absentofworkasearly;
				    }
			    }
			    if((allabsent && !atValue)||(swipecardnum==4 && atValue==1))
			    {
			        snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						strftime('%%H:%%M:%%S','%s','+%d minute') and strftime('%%H:%%M:%%S',CreatedTime)>=\
						strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,workstart,tolerateoflate,morningworkoff,
						tolerateofearly); 
					if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select108 err.\n");
					amabsent=gatoi(rowsnum);
					if(!amabsent)	 
					{
					    absentofwork += 0.5;
					}else
					{
					    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				        strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,morningworkoff,tolerateofearly);
			            if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select109 err.\n");
				        absentamearlytimes = gatoi(rowsnum);
				        if(!absentamearlytimes)
				        {
				            absentofwork += absentofworkasearly;
				        }
					}
			    }
//			    printf("absentofwork absentofwork early days:%.1f amabsent:%d absentamearlytimes:%d \n",absentofwork,
//				    amabsent,absentamearlytimes);	
			    if(swipecardnum==4 && !atValue && absentearlytimes && absentlatetimes && allabsent && amabsent && pmabsent)
			    {
			        snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				        staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					    gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
						gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					    CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				        strftime('%%H:%%M:%%S','%s','-%d minute') and strftime('%%H:%%M:%%S',CreatedTime)<=\
						strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
						*(dbResult+((i-1)*sncols)+(3-1)),h0,d,morningworkoff,tolerateofearly,afternoonworkstart,
						tolerateoflate);
				    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select110 err.\n");	
			        int middleattendance = gatoi(rowsnum);
				    if(!middleattendance)
				    {
				        absentofwork += absentofworkasearly;
					    absentofwork += absentofworkaslate;
				    }
				    if(middleattendance==1)
				    {
				        absentofwork += absentofworkasearly;
				    }
			    }
//				printf("middleattendance:%d\n",middleattendance); 
			}
			
			int lts=1;
			//late times.		
			if(d==0)
			{
    			snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				   strftime('%%H:%%M:%%S','%s','+%d minute');",h0,workstart,extenoflate);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select111 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(d==e)
			{			   
                snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')>=\
				    strftime('%%H:%%M:%%S','%s','+%d minute');",h1,workstart,extenoflate);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select112 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(lts && absentlatetimes && allabsent && amabsent && (!atValue || atValue==1))
			{
			    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				    staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
					gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)<=\
					strftime('%%H:%%M:%%S','%s','+%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
					*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workstart,extenoflate);   
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select113 err.\n");
				if(!gatoi(rowsnum))
				{
				    latetimes+=1;	
			    }				
            }
			lts=1;
			//AM early times.
			if(d==0)
			{
    			snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				   strftime('%%H:%%M:%%S','%s','-%d minute');",h0,morningworkoff,extenofearly);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select114 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(d==e)
			{			   
                snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				    strftime('%%H:%%M:%%S','%s','-%d minute');",h1,morningworkoff,extenofearly);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select115 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(lts && swipecardnum==4 && absentamearlytimes && allabsent && amabsent && atValue==1)
			{
			    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				    staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
					gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				    strftime('%%H:%%M:%%S','%s','-%d minute');",*(dbResult+((i-1)*sncols)+(2-1)),
					*(dbResult+((i-1)*sncols)+(3-1)),h0,d,morningworkoff,extenofearly);   
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select116 err.\n");
				if(!gatoi(rowsnum))
				{
				    amearlytimes += 1;	 			
			    }				
			}
			lts=1;	
			//PM late times.
            if(d==0)
			{
    			snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')>=\
				   strftime('%%H:%%M:%%S','%s','+%d minute');",h0,afternoonworkstart,extenoflate);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select117 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(d==e)
			{			   
                snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				    strftime('%%H:%%M:%%S','%s','+%d minute');",h1,afternoonworkstart,extenoflate);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select118 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(lts && swipecardnum==4 && absentpmlatetimes && allabsent && pmabsent&& atValue==2)
			{
			    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				    staffbasesetting where staffnum='%s' and (select attendancecheck from \
					gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
					gatenum=accessrecord.gatenum FROM staffbasesetting) and staffname='%s') and \
					strftime('%%Y-%%m-%%d',CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and\
					strftime('%%H:%%M:%%S',CreatedTime)<=strftime('%%H:%%M:%%S','%s','+%d minute');",
					*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,d,afternoonworkstart,
					extenoflate);   
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select119 err.\n");
				if(!gatoi(rowsnum))
				{
				    pmlatetimes += 1;
			    }				
			}
			lts=1;
			//early times.
			if(d==0)
			{
    			snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				   strftime('%%H:%%M:%%S','%s','-%d minute');",h0,workoff,extenofearly);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select120 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(d==e)
			{			   
                snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				    strftime('%%H:%%M:%%S','%s','-%d minute');",h1,workoff,extenofearly);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select121 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(lts && absentearlytimes!=0 && allabsent && pmabsent && (atValue==0 || atValue==2))
			{
			    snprintf(sqlstr,800,"select COUNT(*) from accessrecord where cardnum=(select cardnum from \
				    staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
					gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)>=\
				    strftime('%%H:%%M:%%S','%s','-%d minute');",
					*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workoff,extenofearly);   
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select122 err.\n");
				if(!gatoi(rowsnum))
				{
				    earlytimes+= 1;	
			    }				
			}
//			printf("latetimes:%d amearlytimes:%d pmlatetimes:%d earlytimes:%d\n",latetimes,amearlytimes,
//			    pmlatetimes,earlytimes);
			lts=1;
			//ALLday overtimes;
			if(d==0)
			{
    			snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				   strftime('%%H:%%M:%%S','%s','+%d minute');",h0,workstart,extenoflate);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select123 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(d==e)
			{			   
                snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')>=\
				    strftime('%%H:%%M:%%S','%s','-%d minute');",h1,workoff,extenofearly);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select124 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(lts && atValue==3)
			{
			    snprintf(sqlstr,800,"SELECT (strftime('%%s',MAX(strftime('%%H:%%M:%%S',CreatedTime)))-strftime('%%s',\
				    MIN(strftime('%%H:%%M:%%S',CreatedTime)))) from accessrecord where cardnum=(select cardnum \
					from staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
					gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',CreatedTime)=\
					strftime('%%Y-%%m-%%d','%s','+%d day');",*(dbResult+((i-1)*sncols)+(2-1)),
					*(dbResult+((i-1)*sncols)+(3-1)),h0,d);   
			    rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);
			    if(rc<0)
                {
//     				printf("dwreadstatistics select125 err.\n");
				}else if(rc==0)
				{
				    overtimes=0;
				}else
				{
				    overtimes+=(atof(rowsnum)/3600.00);				
			    }               				
			}
			if(lts && allabsent && pmabsent && atValue==0)
			{
			    snprintf(sqlstr,800,"SELECT (strftime('%%s',MAX(strftime('%%H:%%M:%%S',CreatedTime)))-\
				    strftime('%%s','%s','+%d minute')) from accessrecord where cardnum=(select cardnum from \
					staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck from \
					gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
					gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',CreatedTime)\
					= strftime('%%Y-%%m-%%d','%s','+%d day') and (strftime('%%s',strftime('%%H:%%M:%%S',\
					CreatedTime))>strftime('%%s','%s','+%d minute'));",workoff,overtimeafter,
					*(dbResult+((i-1)*sncols)+(2-1)),*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workoff,overtimeafter);   
			    rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);
			    if(rc<0)
                {
//     				printf("dwreadstatistics select128 err.\n");
				}else if(rc==0)
				{
				    overtimes=0;
				}else
				{
				    overtimes+=(atof(rowsnum)/3600.00);				
			    }                  				
			}
			lts=1;
			//PM overtimes;
			if(d==0)
			{
    			snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				   strftime('%%H:%%M:%%S','%s','+%d minute');",h0,afternoonworkstart,extenoflate);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select129 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(d==e)
			{			   
                snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')>=\
				    strftime('%%H:%%M:%%S','%s','+%d minute');",h1,afternoonworkstart,extenoflate);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select130 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(lts && atValue==1)
			{
			    snprintf(sqlstr,800,"SELECT (strftime('%%s',MAX(strftime('%%H:%%M:%%S',CreatedTime)))-\
				    strftime('%%s','%s')) from accessrecord where cardnum=(select cardnum from staffbasesetting \
					where staffnum='%s' and staffname='%s') and (select attendancecheck from gatesetting where \
					gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
					gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',CreatedTime)=\
					strftime('%%Y-%%m-%%d','%s','+%d day') and (strftime('%%s',strftime('%%H:%%M:%%S',\
					CreatedTime))>strftime('%%s','%s'));",afternoonworkstart,*(dbResult+((i-1)*sncols)+(2-1)),
					*(dbResult+((i-1)*sncols)+(3-1)),h0,d,afternoonworkstart);   
			    rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);
			    if(rc<0)
                {
//     				printf("dwreadstatistics select131 err.\n");
				}else if(rc==0)
				{
				    overtimes=0;
				}else
				{
				    overtimes+=(atof(rowsnum)/3600.00);				
			    }                				
			}
			lts=1;
			//AM overtimes;
			if(d==0)
			{
    			snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')<=\
				   strftime('%%H:%%M:%%S','%s','+%d minute');",h0,workstart,extenoflate);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select132 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(d==e)
			{			   
                snprintf(sqlstr,640,"select COUNT(*) where strftime('%%H:%%M:%%S','%s')>=\
				    strftime('%%H:%%M:%%S','%s','+%d minute');",h1,workstart,extenoflate);
			    if(dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac)<0) printf("dwreadstatistics select133 err.\n");	
			    lts=gatoi(rowsnum);
            }
			if(lts && atValue==2)
			{
				snprintf(sqlstr,1023,"SELECT (strftime('%%s',MAX(strftime('%%H:%%M:%%S',CreatedTime)))\
				    -strftime('%%s','%s')) from accessrecord where strftime('%%H:%%M:%%S',CreatedTime)<\
					strftime('%%H:%%M:%%S','%s') AND cardnum=(select cardnum \
					from staffbasesetting where staffnum='%s' and staffname='%s') and (select attendancecheck \
					from gatesetting where gatenum=accessrecord.gatenum)='yes'  AND (SELECT gatenum='all' OR \
					gatenum=accessrecord.gatenum FROM staffbasesetting) and strftime('%%Y-%%m-%%d',\
					CreatedTime)=strftime('%%Y-%%m-%%d','%s','+%d day') and strftime('%%H:%%M:%%S',CreatedTime)\
					<strftime('%%H:%%M:%%S','%s','+%d minute');",workstart,morningworkoff,*(dbResult+((i-1)*sncols)+(2-1)),
					*(dbResult+((i-1)*sncols)+(3-1)),h0,d,workstart,extenoflate); 
				rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);
			    if(rc<0)
                {
//     				printf("dwreadstatistics select134 err.\n");
				}else if(rc==0)
				{
				    overtimes=0;
				}else
				{
				    overtimes+=(atof(rowsnum)/3600.00);				
			    }
			}
//			printf("overtimes:%.2f\n",overtimes);			
			atValue=0;			
        }
			
        //out tab
		if(swipecardnum==2)
		{
		    for(j=1;j<=(sncols+5);j++)
		    {
			    if(i==1&&j==1)
			    {			    
				    sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"pagemax\":\"%d\",\"formpagenum\":\"%d\",\"swipecardnum\":\"2\",\
					    \"s%d_%d\":\"%s\"",snrows,(sncols+5),pagemax,formpagenum,i,j-1,*(dbResult+((i-1)*sncols)+(j-1)));
			        strcat(staffbasesettingtab,s);
		        }else if(j<=sncols)
			    {
			        sprintf(s,",\"s%d_%d\":\"%s\"",i,j-1,*(dbResult+((i-1)*sncols)+(j-1)));
			        strcat(staffbasesettingtab,s);
			    }else if(j==sncols+1)
			    {
			        sprintf(s,",\"s%d_%d\":\"%d\"",i,j-1,latetimes);
				    strcat(staffbasesettingtab,s);
			    }else if(j==sncols+2)
			    {
			        sprintf(s,",\"s%d_%d\":\"%d\"",i,j-1,earlytimes);
				    strcat(staffbasesettingtab,s);
			    }else if(j==sncols+3)
			    {
			        sprintf(s,",\"s%d_%d\":\"%.2f\"",i,j-1,overtimes);
				    strcat(staffbasesettingtab,s);
			    }else if(j==sncols+4)
			    {
			        sprintf(s,",\"s%d_%d\":\"%.1f\"",i,j-1,absentofwork);
				    strcat(staffbasesettingtab,s);
			    }else if(j==sncols+5)
			    {
			        sprintf(s,",\"s%d_%d\":\"%d\"",i,j-1,offtimes);
				    strcat(staffbasesettingtab,s);
			    }
            }				
		}else if(swipecardnum==4)
		{
		    for(j=1;j<=(sncols+7);j++)
		    {
			    if(i==1&&j==1)
			    {			    
				    sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"pagemax\":\"%d\",\"formpagenum\":\"%d\",\"swipecardnum\":\"4\",\
					    \"s%d_%d\":\"%s\"",snrows,(sncols+7),pagemax,formpagenum,i,j-1,*(dbResult+((i-1)*sncols)+(j-1)));
			        strcat(staffbasesettingtab,s);
		        }else if(j<=sncols)
			    {
			        sprintf(s,",\"s%d_%d\":\"%s\"",i,j-1,*(dbResult+((i-1)*sncols)+(j-1)));
			        strcat(staffbasesettingtab,s);
			    }else if(j==sncols+1)
			    {
			        sprintf(s,",\"s%d_%d\":\"%d\"",i,j-1,latetimes);
				    strcat(staffbasesettingtab,s);
			    }else if(j==sncols+2)
			    {
			        sprintf(s,",\"s%d_%d\":\"%d\"",i,j-1,amearlytimes);
				    strcat(staffbasesettingtab,s);
			    }else if(j==sncols+3)
				{
				    sprintf(s,",\"s%d_%d\":\"%d\"",i,j-1,pmlatetimes);
				    strcat(staffbasesettingtab,s);
				}else if(j==sncols+4)
				{
				    sprintf(s,",\"s%d_%d\":\"%d\"",i,j-1,earlytimes);
				    strcat(staffbasesettingtab,s);
				}else if(j==sncols+5)
			    {
			        sprintf(s,",\"s%d_%d\":\"%.2f\"",i,j-1,overtimes);
				    strcat(staffbasesettingtab,s);
			    }else if(j==sncols+6)
			    {
			        sprintf(s,",\"s%d_%d\":\"%.1f\"",i,j-1,absentofwork);
				    strcat(staffbasesettingtab,s);
			    }else if(j==sncols+7)
			    {
			        sprintf(s,",\"s%d_%d\":\"%d\"",i,j-1,offtimes);
				    strcat(staffbasesettingtab,s);
			    }	
            }				
		}
        //write DB
        if(swipecardnum==2)
		{		    	
			snprintf(sqlstr,1023,"INSERT INTO attendanceform(skid,staffnum,staffname,departmentname,latetimes,\
			    earlytimes,overtimes,absentofwork,offtimes) VALUES('%s','%s','%s','%s',\
				'%d','%d','%.2f','%.1f','%d');",*(dbResult+((i-1)*sncols)+(1-1)),*(dbResult+((i-1)*sncols)+(2-1)),\
				*(dbResult+((i-1)*sncols)+(3-1)),*(dbResult+((i-1)*sncols)+(4-1)),latetimes,earlytimes,\
				overtimes,absentofwork,offtimes);
		    rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);	
		}else if(swipecardnum==4)
        {	
			snprintf(sqlstr,1023,"INSERT INTO attendanceform(skid,staffnum,staffname,departmentname,latetimes,\
			    amearlytimes,pmlatetimes,earlytimes,overtimes,absentofwork,offtimes) VALUES('%s','%s','%s','%s',\
				'%d','%d','%d','%d','%.2f','%.1f','%d');",*(dbResult+((i-1)*sncols)+(1-1)),*(dbResult+((i-1)*sncols)+(2-1)),\
				*(dbResult+((i-1)*sncols)+(3-1)),*(dbResult+((i-1)*sncols)+(4-1)),latetimes,amearlytimes\
				,pmlatetimes,earlytimes,overtimes,absentofwork,offtimes);
		    rc = dwrdwtDBstac(sqlstr,(unsigned char**)&rowsnum,connstac);	
		}
        //recover	
        absentofwork=0.0;
		latetimes=0;
		earlytimes=0;
		pmlatetimes=0;
		amearlytimes=0;
		offtimes=0;
		overtimes=0.00;    
	    absentamearlytimes=0;
        absentpmlatetimes=0; 
  		allabsent=1;
		amabsent=1;
		pmabsent=1;
		middleattendance=0;
		absentlatetimes=1;
		absentamearlytimes=1;
//		websWrite(wp, T("%d"),i);
//		websDone(wp, 200);
	}	
	strcat(staffbasesettingtab,"}");
	sqlite3_close(connstac);
//    printf("%s\n",staffbasesettingtab);
    websJson(wp);	
	websWrite(wp, T("%s"),staffbasesettingtab);
//	}
//    websFooter(wp);
	websDone(wp, 200);
	for(i=0;i<112;i++)
	{
	    bfree(B_L,dbResult[i]);
	}
	bfree(B_L,rowsnum);
	bfree(B_L,s);
	bfree(B_L,staffbasesettingtab);
	bfree(B_L,sqlstr);
	bfree(B_L,strbuf);
	bfree(B_L,pagei);
	bfree(B_L,h0);
	bfree(B_L,h1);
    bfree(B_L,sIndex1);
	bfree(B_L,sIndex2);
    return;
}

static void dwsetformpage(webs_t wp, char_t *path, char_t *query)
{
	websText(wp);
	if(!query || (!strlen(query)))
	{
	    websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
	char formpagenum=1;
	if(gatoi(query)>=1) formpagenum=gatoi(query);
//	printf("query:%s formpagenum:%d\n",query,formpagenum);
	websOK(wp);
	websDone(wp, 200);
}

//int accesspagenum = 1;
//static int dwreadaccess(int eid, webs_t wp, int argc, char_t **argv)
static void dwreadaccess(webs_t wp, char_t *path, char_t *query)
{
//    printf("query:%s %d\n",query,__LINE__);
    if(!query || (!strlen(query)))
    {       
        websText(wp);
		websWrite(wp, T("INPUT NULL.\n"));
        websDone(wp, 200);
        return;
    }
    char_t* yeshuchuan[24]={0};

//    printf("query:%s %d\n",query,__LINE__);
    char_t* sIndex1=NULL;

    if((sIndex1=strstr(query,"\"yeshu\":\""))!=NULL)
    {

        strncpy(yeshuchuan,sIndex1+9,23);

        sIndex1=strchr(yeshuchuan,'"');
        if(sIndex1) *(sIndex1)='\0';
//        printf("yeshuchuan:%s %d\n",yeshuchuan,__LINE__);       
    }
    int yeshu=1;
    if(strlen(yeshuchuan)) yeshu = atoi(yeshuchuan);
	unsigned char yehangshu = 16;
	int pagestart=1;
	int pageend=1;
//    printf("yeshu:%d %d\n",yeshu,__LINE__);
    pagestart=yehangshu*yeshu-yehangshu;
    pageend=yehangshu;
		
	unsigned char i,j;   
	char_t* s;
	s = balloc(B_L,49);	
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* accesstab;
	accesstab = balloc(B_L,2048);
	strcpy(accesstab,"{\0");
	char_t* dbResult[84];
	for(i=0;i<84;i++)
	{
	    dbResult[i] = balloc(B_L,33);	
	}
	char_t* rowsnum;
	rowsnum = balloc(B_L,33);	
	strcpy(sqlstr,"select COUNT(*) from accessrecord;");
	if(dwreadwriteDB(sqlstr,(unsigned char**)&rowsnum,&ncols,&nrows)<0) printf("db err.%s %d\n",sqlstr,__LINE__);
//	printf("rowsnum=%s\n",rowsnum);
	int pagemax=1;
	pagemax = (((gatoi(rowsnum))/(yehangshu*1.0))-(int)((gatoi(rowsnum))/(yehangshu*1.0)))>0.?(int)((gatoi(rowsnum))/(yehangshu*1.0))+1:(int)((gatoi(rowsnum))/(yehangshu*1.0));	
	if(pagemax<1) pagemax=1;
//	printf("pagemax=%d\n",pagemax);
	if(yeshu>pagemax) yeshu=pagemax;
	pagestart=yehangshu*yeshu-yehangshu;
    pageend=yehangshu;	
	snprintf(sqlstr,255,"select rowid,cardnum,gatenum,accessstat,CreatedTime from accessrecord order by rowid desc limit %d,%d;",pagestart,pageend);
//    printf("sqlstr:%s\n",sqlstr);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&dbResult,&ncols,&nrows)<0) printf("db err.%s %d\n",sqlstr,__LINE__);
//	printf("nrows=%d,ncols=%d %d\n",nrows,ncols,__LINE__);
//    if(nrows)
//    {	
	    for(i=1;i<=nrows;i++)
	    {
	        for(j=1;j<=ncols;j++)
		    {
//			    if(i==1&&j==1)
//			    {
//			        sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"pagemax\":\"%d\",\"accesspagenum\":\"%d\"\
					    ,\"s%d_%d\":\"%s\"",nrows,ncols,pagemax,accesspagenum,i,j-1,
//						*(dbResult+((i-1)*ncols)+(j-1)));
//			        strcat(accesstab,s);
//		        }else
//			    {
			        snprintf(s,48,"\"s%d_%d\":\"%s\",",i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
			        strcat(accesstab,s);
					if(strlen(accesstab)>=1905) break;
//			    }
		    }		
	    }
//    }
	snprintf(sqlstr,95,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"pagemax\":\"%d\",\"accesspagenum\":\"%d\"}",nrows,ncols,pagemax,yeshu);		
	strcat(accesstab,sqlstr);
//    printf("accesstab:%s Length:%d %d\n",accesstab,strlen(accesstab),__LINE__);	
	websJson(wp);
    websWrite(wp, T("%s"),accesstab);
    websDone(wp,200);	
	for(i=0;i<84;i++)
	{
	    bfree(B_L,dbResult[i]);
	}
	bfree(B_L,rowsnum);
	bfree(B_L,s);
	bfree(B_L,accesstab);
	bfree(B_L,sqlstr);
	return;
}

static void dwsetaccesspage(webs_t wp, char_t *path, char_t *query)
{	
/*	websText(wp);
	if(!query || (!strlen(query)))
	{	    
		websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
	if(gatoi(query)>=1) accesspagenum=gatoi(query);
//	printf("query:%s accesspagenum:%d\n",query,accesspagenum);
	websOK(wp);
	websDone(wp, 200);*/
}

static void dwviewextentaff(webs_t wp, char_t *path, char_t *query)
{	
	if(!query || (!strlen(query)))
	{	    
		websText(wp);
		websWrite(wp, T("%s<br/>"),"INPUT NULL.");
		websDone(wp, 200);
		return;
	}
	static unsigned char i,j;   
	char_t* s;
	s = balloc(B_L,49);	
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* staffextntab;
	staffextntab = balloc(B_L,1024);
	strcpy(staffextntab,"{\0");
	char_t* dbResult[20];
	for(i=0;i<20;i++)
	{
	    dbResult[i] = balloc(B_L,33);	
	}
    char_t* skid;
    skid = balloc(B_L,24);
	char_t* strbuf;
	strbuf = balloc(B_L,48);
	strcpy(strbuf,query);
//	printf("strbuf:%s %d\n",strbuf,__LINE__);
	char_t* sIndex1;
	char_t* sIndex2;
    if((sIndex1=strstr(strbuf,"\"skid\":\""))!=NULL)
	{
//	    sIndex1=strstr(strbuf,"\"skid\":\"")+8;
//		printf("strbuf1:%s %d\n",sIndex1,__LINE__);
        strncpy(skid,sIndex1+8,23);
//		printf("strbuf2:%s %d\n",skid,__LINE__);
        sIndex2=strchr(skid,'"');
        if(sIndex2) *(sIndex2)='\0';
//        printf("skid:%s %d\n",skid,__LINE__);		
	}
	snprintf(sqlstr,255,"select staffnum,staffname,staffgender, staffage, picfilename,departmentID,entrancevalitystart,entrancevalityend,leavevalitystart,leavevalityend from staffbasesetting where rowid ='%s';",skid);
//    printf("sqlstr:%s %d\n",sqlstr,__LINE__);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&dbResult,&ncols,&nrows)<0) printf("dwreadaccess select1 err.%d\n",__LINE__);
//	printf("nrows=%d,ncols=%d %d\n",nrows,ncols,__LINE__);
	for(i=1;i<=nrows;i++)
	{
	    for(j=1;j<=ncols;j++)
	    {
//	        if(i==1&&j==1)
//		    {
//		        sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"s%d_%d\":\"%s\""
//     			    ,nrows,ncols,i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
//		        strcat(staffextntab,s);
//		    }else
//		    {
		        snprintf(s,48,"\"s%d_%d\":\"%s\",",i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
		        strcat(staffextntab,s);
				if(strlen(staffextntab)>=928) break;
//		    }
		}		
	}
	snprintf(s,48,"\"nrows\":\"%d\",\"ncols\":\"%d\"}",nrows,ncols);
	strcat(staffextntab,s);
//    printf("%s %d\n",staffextntab,__LINE__);
	char_t* srcstr;
	srcstr=balloc(B_L,128);
	char_t* desstr;
	desstr=balloc(B_L,128);
	snprintf(srcstr,127,"/mnt/user/pcis/%s",*(dbResult+4));
	snprintf(desstr,127,"/etc_ro/web/door/pcis/%s",*(dbResult+4));
	doSystem("rm /etc_ro/web/door/pcis/*");
    doSystem("cp %s %s", srcstr,desstr);
	websJson(wp);
	websWrite(wp, T("%s"),staffextntab);
	websDone(wp, 200);
	bfree(B_L,srcstr);
	bfree(B_L,desstr);

	for(i=0;i<20;i++)
	{
	    bfree(B_L,dbResult[i]);
	}	
	bfree(B_L,s);
	bfree(B_L,staffextntab);
	bfree(B_L,skid);
	bfree(B_L,sqlstr);
	bfree(B_L,strbuf);
	return;
}

static void dwDelextenstaff(webs_t wp, char_t *path, char_t *query)
{
//    printf("%s\n",query);
    websHeader(wp);	
	if(!query || (!strlen(query)))
	{	    
		websWrite(wp, T("<script language=\"JavaScript\">alert('query NULL.');</script><br/>"));
		websDone(wp, 200);
		return;
	}
	char_t* rtl;
    rtl = balloc(B_L,33);
	char_t* strbuf;
	strbuf = balloc(B_L,64);
	strcpy(strbuf,query);
//	printf("strbuf:%s\n",strbuf);
	char_t* staffnum;
	staffnum=balloc(B_L,24);
	char_t* staffname;
	staffname=balloc(B_L,24);	
	char_t* sIndex1;
	char_t* sIndex2;
    if(strstr(strbuf,"staffnum"))
	{
	    sIndex1=strstr(strbuf,"\"staffnum\":\"")+12;
//		printf("strbuf1:%s\n",sIndex1);
        strncpy(staffnum,sIndex1,23);
//		printf("strbuf2:%s\n",staffnum);
        sIndex2=strchr(staffnum,'"');
        *(sIndex2)='\0';
//        printf("staffnum:%s \n",staffnum);		
	}
	if(strstr(strbuf,"staffname"))
	{
	    sIndex1=strstr(strbuf,"\"staffname\":\"")+13;
//		printf("strbuf1:%s\n",sIndex1);
        strncpy(staffname,sIndex1,23);
//		printf("strbuf2:%s\n",staffname);
        sIndex2=strchr(staffname,'"');
        *(sIndex2)='\0';
//        printf("staffname:%s \n",staffname);		
	}
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	snprintf(sqlstr,255,"update staffbasesetting set staffgender='', staffage=0, picfilename='' where \
	    staffnum='%s' and staffname='%s';",staffnum,staffname);
//    printf("sqlstr:%s\n",sqlstr);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&rtl,&ncols,&nrows)<0) 
	{
	    printf("dwDelextenstafff delete err.\n");
	    websWrite(wp, T("<script language=\"JavaScript\">alert('dwDelextenstaff err.');</script><br/>"));
	}else
	{	
    }
	websDone(wp, 200);
	bfree(B_L,rtl);
}	

static int dwreadforce(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* s;
	s = balloc(B_L,49);	
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
	char_t* staffbasesettingtab;
	staffbasesettingtab = balloc(B_L,2048);
	strcpy(staffbasesettingtab,"{\0");
	char_t* dbResult[112];
	static unsigned char i,j;
	for(i=0;i<112;i++)
	{
	    dbResult[i] = balloc(B_L,33);	
	} 
	snprintf(sqlstr,255,"select rowid,forcefrom,forceto,forcenote from attendanceforce;");
//    printf("sqlstr:%s\n",sqlstr);
	if(dwreadwriteDB(sqlstr,(unsigned char**)&dbResult,&ncols,&nrows)<0) printf("dwreadforce select1 err.\n");
//	printf("nrows=%d,ncols=%d\n",nrows,ncols);
//    if(nrows)	
//	{
	    for(i=1;i<=nrows;i++)
	    {
	        for(j=1;j<=ncols;j++)
		    {
//			    if(i==1&&j==1)
//			    {
//			        sprintf(s,"\"nrows\":\"%d\",\"ncols\":\"%d\",\"s%d_%d\":\"%s\""
//     				    ,nrows,ncols,i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
//			        strcat(staffbasesettingtab,s);
//		        }else
//			    {
			        snprintf(s,48,"\"s%d_%d\":\"%s\",",i,j-1,*(dbResult+((i-1)*ncols)+(j-1)));
			        strcat(staffbasesettingtab,s);
					if(strlen(staffbasesettingtab)>=1952) break;
//			    }
		    }		
	    }
//    }
	snprintf(s,48,"\"nrows\":\"%d\",\"ncols\":\"%d\"}",nrows,ncols);
	strcat(staffbasesettingtab,s);
//    printf("%s\n",staffbasesettingtab);	
	websWrite(wp, T("%s"),staffbasesettingtab);
	for(i=0;i<112;i++)
	{
	    bfree(B_L,dbResult[i]);
	}
	bfree(B_L,s);
	bfree(B_L,staffbasesettingtab);
	bfree(B_L,sqlstr);
	return 0;
}

static void dwDelforce(webs_t wp, char_t *path, char_t *query)
{
//    printf("%s\n",query);
    websText(wp);	
	if(!query || (!strlen(query)))
	{	    
		websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
//		bfree(B_L,rtl);
		return;
	}
	char_t* rtl;
    rtl = balloc(B_L,33);
	int ncols=0,nrows=0;
	if(dwreadwriteDB(query,(unsigned char**)&rtl,&ncols,&nrows)<0) 
	{
//	    printf("dwDelforce delete err.\n");
//		websText(wp);
	    websWrite(wp, T("%s"),"dwDelforce err.");
	}else
	{
//	    websHeader(wp);
//        websWrite(wp, T("%s"),"200");
//		websWrite(wp, T("HTTP/1.0 200 OK\n"));		
    }
	websDone(wp, 200);
	bfree(B_L,rtl);
}

static void dwwriteforce(webs_t wp, char_t *path, char_t *query)
{
	char_t*  content;
    content = balloc(B_L,64);
	char_t* sqlstr;
	sqlstr = balloc(B_L,256);
	int ncols=0,nrows=0;
//	char_t* holidayname = "\0";
	char_t* forcefrom = "\0";
	char_t* forceto = "\0";
	char_t* forcenote = "null";
	int rc = 0;
    unsigned char* staffnumbuff[1];
	staffnumbuff[0] = balloc(B_L,33);
//	holidayname = websGetVar(wp, T("holidayname"), T(""));
	forcefrom = websGetVar(wp, T("forcefrom"), T(""));
	forceto = websGetVar(wp, T("forceto"), T(""));
	forcenote = websGetVar(wp, T("forcenote"), T(""));
//	printf("forcefrom:%s,forceto:%s,forcenote:%s\n",forcefrom,forceto,forcenote);
	if((!forcefrom)||!(*forcefrom)||(!forceto)||!(*forceto)
	    ||strlen(forcefrom)>21||strlen(forceto)>21||strlen(forcenote)>28)
	{
//	    printf("dwwriteforce_NULL or too long.\n");
//		sprintf(content,"dwwriteforce_NULL or too long.");
//		dwwrite(content);
		sprintf(content,"INPUT NULL.");
		websHeader(wp);	
		websWrite(wp, T("<script language=\"JavaScript\">alert(%s);</script><br/>"),content);
		websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href=\"/door/\
		    attendanceforce.asp\",5000);</script><br/>"));				    		
	}else
	{
		    rc = snprintf(sqlstr,255,"INSERT INTO attendanceforce(forcefrom,forceto,forcenote)\
			    VALUES(\"%s\",\"%s\",\"%s\");",forcefrom,forceto,forcenote);	       
		    websHeader(wp);
			if(dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows)<0)
			{
//			    websText(wp);
				websWrite(wp, T("<script language=\"JavaScript\">alert(%s);</script><br/>"),"dwwriteforce WRITE \
				    DB ERR.");
//				websDone(wp, 200); 
//				return;
			}else
            {			
                websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href=\"/door/attendanceforce.asp\",3000);</script><br/>"));
            } 				
//	        websFooter(wp);
//	        websDone(wp, 200);      		
    }
	websFooter(wp);
	websDone(wp, 200);
	bfree(B_L,staffnumbuff[0]);
	bfree(B_L,content);
	bfree(B_L,sqlstr);
//	printf("free staffnumbuff[0] ok\n");
}

static void signatureSet(webs_t wp, char_t *path, char_t *query)
{
    char_t* password="123456";
	char_t* forcepass="999999";	
	password = websGetVar(wp,T("password"),T("123456"));	
    forcepass = websGetVar(wp,T("forcepass"),T("999999"));   	
	if(!password||!(*password)||!forcepass||!(*forcepass)||(strlen(password)>6||strlen(forcepass)>6))
	{
	    websHeader(wp);
        if (!strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))		
	        websWrite(wp, T("password or forcepass NULL or too long.<br/>"));
		if (strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))		
	        websWrite(wp, T("开门密码或胁迫密码为空或太长。<br/>"));              //don't use '' instead of ""
		websWrite(wp, T("<script language=\"javascript\">self.setTimeout(window.location.href='/door/gatesetting.asp',\
		    2000);</script><br/>"));
	    websFooter(wp);
	    websDone(wp, 200);
//		printf("password or forcepass NULL.\n");
		return;
	}
    char_t* sqls;
    sqls=balloc(B_L,128);
	strcpy(sqls,"\0");
    if(!sqls) perror("sqls");
	int ncols=0,nrows=0;	
    unsigned char* dbData;	
	dbData = balloc(B_L,33); 	
	snprintf(sqls,127,"update gatesetting set password='%s',forcepass='%s';",password,forcepass);
	websHeader(wp);	
	if(dwreadwriteDB(sqls,(unsigned char**)&dbData,&ncols,&nrows)<0)
    {
    	websWrite(wp, T("<script language=\"javascript\">alert('signatureSet DB err.');</script><br/>"));
//		printf("signatureSet err.\n");
	}else
	{		
	    if (!strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))
		    websWrite(wp, T("<script language=\"javascript\">alert('password and forcepass set up OK.');</script><br/>"));
		if (strcmp(nvram_get(RT2860_NVRAM, "Language"), "en"))
		    websWrite(wp, T("<script language=\"javascript\">alert(\"开门密码与胁迫密码设置成功。\");</script><br/>"));      //don't use '' instead of ""
//		printf("password:%s forcepass:%s\n",password,forcepass); 
	}
	websWrite(wp, T("<script language=\"javascript\">self.setTimeout(window.location.href='/door/gatesetting.asp',\
	    5000);</script><br/>"));
	websFooter(wp);
	websDone(wp, 200);	
	bfree(B_L,sqls);
	bfree(B_L,dbData);
}

static int getSnum(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* snum;
	int rc;
	snum = balloc(B_L,64);	
    FILE* snumfile=fopen(SNUMFILEPATH,"r");
	if(snumfile)
	{
	    fseek(snumfile,0,SEEK_END);
		int count = ftell(snumfile);
	    fseek(snumfile,0,SEEK_SET);
//		strcpy(snum,"\0");
//	    printf("snum:%s %d\n",snum,__LINE__);
		rc=fread(snum,sizeof(char_t),count,snumfile);
        if(count<64) *(snum+count) = '\0';	    
//		printf("snum:%s count:%ld size:%d rc:%d %d\n",snum,count,sizeof(char_t),rc,__LINE__);
//		snprintf(snum,count,"%s",snumfile);
//		printf("snum:%s count:%ld size:%d rc:%d %d\n",snum,count,sizeof(char_t),rc,__LINE__);
		fclose(snumfile);
	}
	if(!(*snum))
	{
	    snprintf(snum,64,"%s",DEFsnum);
	}
/*	strcpy(snum,DEFDEVNUM);
	unsigned char* sn = (unsigned char*)nvram_bufget(RT2860_NVRAM, "seriernum");
	if(*sn) snprintf(snum,64,"%s",sn);*/
	rc = websWrite(wp, T("%s"),snum);
	bfree(B_L,snum);
	return rc;
}

static int getcmdresult(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* WebADDR;
	WebADDR = balloc(B_L,96);
//	strcpy(WebADDR,"\0");
    FILE* ipfile=fopen(cmdresultFile,"r");
	if(ipfile)
	{
	    fseek(ipfile,0,SEEK_END);
		int count = ftell(ipfile);
		fseek(ipfile,0,SEEK_SET);
	    fread(WebADDR,sizeof(char),count,ipfile);
	    if(count<96) *(WebADDR+count) = '\0';
		fclose(ipfile);
	}
	if(!(*WebADDR))
	{
	    snprintf(WebADDR,96,"%s",DEFcmdresult);
	}
/*	strcpy(WebADDR,DEFCMDRESULTPATH);
	unsigned char* cmdpath = (unsigned char*)nvram_bufget(RT2860_NVRAM, "cmdresultpath");
	if(*cmdpath)
	{
		snprintf(WebADDR,96,"%s",cmdpath);
		printf("WebADDR:%s cmdpath:%s %d\n",WebADDR,cmdpath,__LINE__);
	}*/
	int rc = websWrite(wp, T("%s"),WebADDR);
	bfree(B_L,WebADDR);
	return rc;
}

static int getrealtime(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* WebADDR;
	WebADDR = balloc(B_L,96);
//	strcpy(WebADDR,"\0");
	FILE* ipfile=fopen(realtimeFile,"r");
	if(ipfile)
	{
	    fseek(ipfile,0,SEEK_END);
		int count = ftell(ipfile);
		fseek(ipfile,0,SEEK_SET);
	    fread(WebADDR,sizeof(char),count,ipfile);
	    if(count<96) *(WebADDR+count) = '\0';
		fclose(ipfile);
	}
	if(!(*WebADDR))
	{
	    strcpy(WebADDR,DEFrealtime);
	}
/* 	strcpy(WebADDR,DEFREALTIMEPATH);
	unsigned char* rlpath = (unsigned char*)nvram_bufget(RT2860_NVRAM, "realtimepath");
	if(*rlpath) snprintf(WebADDR,96,"%s",rlpath);*/
	int rc = websWrite(wp, T("%s"),WebADDR);
	bfree(B_L,WebADDR);
	return rc;
}

static int getDetectDevice(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* WebADDR;
	WebADDR = balloc(B_L,96);
//	strcpy(WebADDR,"\0");
   FILE* ipfile=fopen(DetectDeviceFile,"r");
	if(ipfile)
	{
	    fseek(ipfile,0,SEEK_END);
		int count = ftell(ipfile);
		fseek(ipfile,0,SEEK_SET);
	    fread(WebADDR,sizeof(char),count,ipfile);
	    if(count<96) *(WebADDR+count) = '\0';
		fclose(ipfile);
	}
	if(!(*WebADDR))
	{
	    strcpy(WebADDR,DEFDetectDevice);
	}
/* 	strcpy(WebADDR,DEFDETECTDEVPATH);
	unsigned char* ddpath = (unsigned char*)nvram_bufget(RT2860_NVRAM, "detectdevicepath");
	if(*ddpath) snprintf(WebADDR,96,"%s",ddpath);*/
	int rc = websWrite(wp, T("%s"),WebADDR);
	bfree(B_L,WebADDR);
	return rc;
}

static int getWebADDR(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* WebADDR;
	WebADDR = balloc(B_L,96);
	int count = 0;
//	strcpy(WebADDR,"\0");
	FILE* webfile=fopen(WebIPFile,"r");
	if(webfile) 
	{	
		fseek(webfile,0,SEEK_END);
		count = ftell(webfile);
//	if(!count) ipflag = 1;
	}
//	if(count)
	if(count>1)
	{
		fseek(webfile,0,SEEK_SET);
		fread(WebADDR,sizeof(char),count,webfile);
		fclose(webfile);
		if(count<96) *(WebADDR+count) = '\0';		
	}else
	{
		FILE* ipfile=fopen(SIPFILEPATH,"r");
		if(ipfile)
		{
			fseek(ipfile,0,SEEK_END);
			int count = ftell(ipfile);
			fseek(ipfile,0,SEEK_SET);
			fread(WebADDR,sizeof(char),count,ipfile);
			if(count<16) *(WebADDR+count) = '\0';
			fclose(ipfile);
		}
	}
	if(!(*WebADDR))
	{
	    strcpy(WebADDR,DEFWebADDR);
	}
/*	strcpy(WebADDR,DEFSERVERIP);
	unsigned char* nvget = (unsigned char*)nvram_bufget(RT2860_NVRAM, "serverweb");
	if(*nvget)
	{
		snprintf(WebADDR,96,"%s",nvget);
	}else
	{
		unsigned char* nvget1 = (unsigned char*)nvram_bufget(RT2860_NVRAM, "serverip");
		if(*nvget1)
		{
			snprintf(WebADDR,96,"%s",nvget1);
		}
	}*/
	int rc = websWrite(wp, T("%s"),WebADDR);
	bfree(B_L,WebADDR);
	return rc;
}

static int getgate0CameraADDR(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* CameraADDR;
	CameraADDR = balloc(B_L,16);
//	strcpy(CameraADDR,"\0");
	FILE* cripfile=fopen(Camera0IPFILE,"r");
	if(cripfile)
	{
	    fseek(cripfile,0,SEEK_END);
		int count = ftell(cripfile);
		fseek(cripfile,0,SEEK_SET);
	    fread(CameraADDR,sizeof(char),count,cripfile);
	    if(count<16) *(CameraADDR+count) = '\0';
		fclose(cripfile);
	}
	if(!(*CameraADDR))
	{
	    strcpy(CameraADDR,DEFCameraIP);
	}
/*	strcpy(CameraADDR,DEFCAMERAIP);
	unsigned char* c0ip = (unsigned char*)nvram_bufget(RT2860_NVRAM, "camera0ip");
	if(*c0ip)
	{		
		strcpy(CameraADDR,c0ip);
	}*/
	int rc = websWrite(wp, T("%s"),CameraADDR);
	bfree(B_L,CameraADDR);
	return rc;
}

static int getgate0CameraPORT(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* CameraPORT;
	CameraPORT = balloc(B_L,16);
    FILE* portfile=fopen(Crport0FILE,"r");
	if(portfile)
	{ 
	    fseek(portfile,0,SEEK_END);
		int count = ftell(portfile);
		fseek(portfile,0,SEEK_SET);
	    fread(CameraPORT,sizeof(char),count,portfile);
	    if(count<16) *(CameraPORT+count) = '\0';
		fclose(portfile);
	}
	if(!(*CameraPORT))
	{
	    strcpy(CameraPORT,DEFCameraPORT);
	}
/*	strcpy(CameraPORT,DEFCAMERAPORT);
	unsigned char* c0ip = (unsigned char*)nvram_bufget(RT2860_NVRAM, "camera0port");
	if(*c0ip)
	{		
		strcpy(CameraPORT,c0ip);
	}*/
	int rc = websWrite(wp, T("%s"),CameraPORT);
	bfree(B_L,CameraPORT);
	return rc;
}

static int getgate1CameraADDR(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* CameraADDR;
	CameraADDR = balloc(B_L,16);
//	strcpy(CameraADDR,"\0");
	FILE* cripfile=fopen(Camera1IPFILE,"r");
	if(cripfile)
	{
	    fseek(cripfile,0,SEEK_END);
		int count = ftell(cripfile);
		fseek(cripfile,0,SEEK_SET);
	    fread(CameraADDR,sizeof(char),count,cripfile);
	    if(count<16) *(CameraADDR+count) = '\0';
		fclose(cripfile);
	}
	if(!(*CameraADDR))
	{
	    strcpy(CameraADDR,DEFCameraIP);
	}
/*	strcpy(CameraADDR,DEFCAMERAIP);
	unsigned char* c0ip = (unsigned char*)nvram_bufget(RT2860_NVRAM, "camera1ip");
	if(*c0ip)
	{		
		strcpy(CameraADDR,c0ip);
	}*/
	int rc = websWrite(wp, T("%s"),CameraADDR);
	bfree(B_L,CameraADDR);
	return rc;
}

static int getgate1CameraPORT(int eid, webs_t wp, int argc, char_t **argv)
{
	char_t* CameraPORT;
	CameraPORT = balloc(B_L,16);
    FILE* portfile=fopen(Crport1FILE,"r");
	if(portfile)
	{ 
	    fseek(portfile,0,SEEK_END);
		int count = ftell(portfile);
		fseek(portfile,0,SEEK_SET);
	    fread(CameraPORT,sizeof(char),count,portfile);
	    if(count<16) *(CameraPORT+count) = '\0';
		fclose(portfile);
	}
	if(!(*CameraPORT))
	{
	    strcpy(CameraPORT,DEFCameraPORT);
	}
/*	strcpy(CameraPORT,DEFCAMERAPORT);
	unsigned char* c0ip = (unsigned char*)nvram_bufget(RT2860_NVRAM, "camera1port");
	if(*c0ip)
	{		
		strcpy(CameraPORT,c0ip);
	}*/
	int rc = websWrite(wp, T("%s"),CameraPORT);
	bfree(B_L,CameraPORT);
	return rc;
}

static int getWebPORT(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* WebPORT;
	WebPORT = balloc(B_L,16);
//	strcpy(WebPORT,"\0");
    FILE* portfile=fopen(SPORTFILEPATH,"r");
	if(portfile)
	{ 
	    fseek(portfile,0,SEEK_END);
		int count = ftell(portfile);
		fseek(portfile,0,SEEK_SET);
	    fread(WebPORT,sizeof(char),count,portfile);
	    if(count<16) *(WebPORT+count) = '\0';
		fclose(portfile);
	}
	if(!(*WebPORT))
	{
	    strcpy(WebPORT,DEFWebPORT);
	}
/*	strcpy(WebPORT,DEFSERVERPORT);
	unsigned char* c0ip = (unsigned char*)nvram_bufget(RT2860_NVRAM, "serverport");
	if(*c0ip)
	{		
		strcpy(WebPORT,c0ip);
	}*/
	int rc = websWrite(wp, T("%s"),WebPORT);
	bfree(B_L,WebPORT);
	return rc;
}

static int getTcpPORT(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* TcpPORT;
	TcpPORT = balloc(B_L,16);
    FILE* portfile=fopen(DWTCPPORTFILEPATH,"r");
	if(portfile)
	{ 
	    fseek(portfile,0,SEEK_END);
		int count = ftell(portfile);
		fseek(portfile,0,SEEK_SET);
	    fread(TcpPORT,sizeof(char),count,portfile);
	    if(count<16) *(TcpPORT+count) = '\0';
		fclose(portfile);
	}
	if(!(*TcpPORT))
	{
	    strcpy(TcpPORT,DEFTCPPORT);
	}
	int rc = websWrite(wp, T("%s"),TcpPORT);
	bfree(B_L,TcpPORT);
	return rc;
}

static int getreQuesttm(int eid, webs_t wp, int argc, char_t **argv)
{
    char_t* reQuesttm;
	reQuesttm = balloc(B_L,16);
//	strcpy(reQuesttm,"\0");
    FILE* reQuesttmfile=fopen(RqtimeFILEPATH,"r");
	if(reQuesttmfile)
	{
	    fseek(reQuesttmfile,0,SEEK_END);
		int count = ftell(reQuesttmfile);
		fseek(reQuesttmfile,0,SEEK_SET);
	    fread(reQuesttm,sizeof(char_t),count,reQuesttmfile);
	    if(count<16) *(reQuesttm+count) = '\0';
		fclose(reQuesttmfile);
	}
	if(!(*reQuesttm))
	{
	    snprintf(reQuesttm,16,"%d",DEFRqtime);
	}
/*	snprintf(reQuesttm,16,"%d",DEFRQTIME);
	unsigned char* c0ip = (unsigned char*)nvram_bufget(RT2860_NVRAM, "request_time");
	if(*c0ip)
	{		
		strcpy(reQuesttm,c0ip);
	}*/
	int rc = websWrite(wp, T("%s"),reQuesttm);
	bfree(B_L,reQuesttm);
	return rc;
}

static int getVersion(int eid, webs_t wp, int argc, char_t **argv)
{
/*     char_t* sVersion;
	sVersion = balloc(B_L,16);
//	strcpy(sVersion,"\0");
   FILE* sVersionfile=fopen(SVERSIONFILEPATH,"r");
	if(sVersionfile)
	{
	    fseek(sVersionfile,0,SEEK_END);
		int count = ftell(sVersionfile);
		fseek(sVersionfile,0,SEEK_SET);
	    fread(sVersion,sizeof(char_t),count,sVersionfile);
	    if(count<16) *(sVersion+count) = '\0';
		fclose(sVersionfile);
	}*/
	int rc = websWrite(wp, T("%s"),SVERSION);
//	bfree(B_L,sVersion);
	return rc;
}

static int getjqfs(int eid, webs_t wp, int argc, char_t **argv)
{
    unsigned char jqfs[16]={DEFJQFS};
    FILE* filep=fopen(DWJQFSLJ,"r");
    if(filep)
    {
        fseek(filep,0,SEEK_END);
        int count = ftell(filep);
        if(count>1)
        {
            fseek(filep,0,SEEK_SET);
            fread(jqfs,sizeof(char),count,filep);            
            if(count<16) *(jqfs+count) = '\0';
        }
        fclose(filep);
    }
/*    unsigned char jqfs[33]={DEFJQFS};
    int ncols=0,nrows=0;
	snprintf(buf,640,"SELECT jqfs FROM gatesetting WHERE gatenum=%d;",gate);
	if(dwreadwriteDB(buf,(unsigned char**)&jqfs,&ncols,&nrows)<0)
    {		
		sqlite3_close(conn);
	    printf("db err.%s %d\n",buf,__LINE__);
		return -1;
	}*/
    websWrite(wp, T("%s"),jqfs);
	return 0;
}

static void setSnum(webs_t wp, char_t *path, char_t *query)
{    
	char_t* snum;
    char_t* WebADDR;
	char_t* WebPORT;
#ifdef TCPMOD
	char_t* TcpPORT;
#else
	char_t* cmdresult;
	char_t* DetectDevice;
#endif
	char_t* jqfs;
    char_t* gate0CameraADDR;
	char_t* gate0crPORT;
	char_t* gate1CameraADDR;
	char_t* gate1crPORT;	
	char_t* request_time;
	
	char_t* realtime;
	
	
//    snum = websGetVar(wp,T("Snum"),T(DEFDEVNUM));
	snum = websGetVar(wp,T("Snum"),T(DEFsnum));
//    WebADDR = websGetVar(wp,T("WebADDR"),T(DEFSERVERIP));
	WebADDR = websGetVar(wp,T("WebADDR"),T(DEFWebADDR));
//	WebPORT =  websGetVar(wp,T("WebPORT"),T(DEFSERVERPORT));
	WebPORT =  websGetVar(wp,T("WebPORT"),T(DEFWebPORT));
#ifdef TCPMOD
	TcpPORT =  websGetVar(wp,T("TcpPORT"),T(DEFTCPPORT));
#else
	cmdresult =  websGetVar(wp,T("cmdresult"),T(DEFcmdresult));
	DetectDevice =  websGetVar(wp,T("DetectDevice"),T(DEFDetectDevice));
#endif
	jqfs =  websGetVar(wp,T("jqfs"),T(DEFJQFS));
//    gate0CameraADDR = websGetVar(wp,T("gate0CameraADDR"),T(DEFCAMERAIP));	
	gate0CameraADDR = websGetVar(wp,T("gate0CameraADDR"),T(DEFCameraIP));
//	gate0crPORT =  websGetVar(wp,T("gate0CameraPORT"),T(DEFCAMERAPORT));
	gate0crPORT =  websGetVar(wp,T("gate0CameraPORT"),T(DEFCameraPORT));
//	gate1CameraADDR = websGetVar(wp,T("gate1CameraADDR"),T(DEFCAMERAIP));
	gate1CameraADDR = websGetVar(wp,T("gate1CameraADDR"),T(DEFCameraIP));
//	gate1crPORT =  websGetVar(wp,T("gate1CameraPORT"),T(DEFCAMERAPORT));
	gate1crPORT =  websGetVar(wp,T("gate1CameraPORT"),T(DEFCameraPORT));
//	request_time =  websGetVar(wp,T("request_time"),T(DEFRQTIME));
	request_time =  websGetVar(wp,T("request_time"),T(DEFRqtime));
//	cmdresult =  websGetVar(wp,T("cmdresult"),T(DEFCMDRESULTPATH));	
//	realtime =  websGetVar(wp,T("realtime"),T(DEFREALTIMEPATH));
	realtime =  websGetVar(wp,T("realtime"),T(DEFrealtime));
//	DetectDevice =  websGetVar(wp,T("DetectDevice"),T(DEFDETECTDEVPATH));

//	printf("snum:%s WebADDR:%s  WebPORT:%s gate0CameraADDR:%s gate0crPORT:%s gate1CameraADDR:%s gate1crPORT:%s %d\n",snum,WebADDR,WebPORT,gate0CameraADDR,gate0crPORT,gate1CameraADDR,gate1crPORT,__LINE__);
	if(!(*snum)||!(*WebADDR)||!(*gate0CameraADDR)||!(*gate1CameraADDR)||!(*WebPORT)||!(*jqfs)||!(*gate0crPORT) ||!(*gate1crPORT)||strlen(snum)>64||strlen(WebADDR)>94||strlen(gate0CameraADDR)>16||strlen(gate1CameraADDR)>16||strlen(WebPORT)>8||strlen(jqfs)>8||strlen(gate0crPORT)>8||strlen(gate1crPORT)>8||strlen(realtime)>96||strlen(cmdresult)>96||strlen(DetectDevice)>96)
	{
//	    printf("setSnum_NULL or too long.\n");
		websHeader(wp);	
		websWrite(wp, T("<script language=\"JavaScript\">alert(\"输入为空或太长。\");</script><br/>"));
		websWrite(wp,T("<script language=\"JavaScript\">self.setTimeout(window.location.href=\"/door/\
		    gatesetting.asp\",5000);</script><br/>"));
		return;		
	}
//	else
//	{	
	FILE* numfile=fopen(SNUMFILEPATH,"w");
	if(numfile)
	{
		fseek(numfile,0,SEEK_SET);
		fwrite(snum,strlen(snum),1,numfile);
		fflush(numfile);
		fclose(numfile);
	}
//		nvram_bufset(RT2860_NVRAM, "seriernum", snum);	
//	    nvram_commit(RT2860_NVRAM);
	if(inet_addr(WebADDR)==INADDR_NONE)
	{
		FILE* webfile=fopen(WebIPFile,"w");
		if(webfile)
		{
			fseek(webfile,0,SEEK_SET);
			fwrite(WebADDR,strlen(WebADDR),1,webfile);
			fflush(webfile);
			fclose(webfile);
		}
		FILE* ipfile=fopen(SIPFILEPATH,"w");
		if(ipfile)
		{
			unsigned char strtmp[2]={"\0"};
			fseek(ipfile,0,SEEK_SET);
			fwrite(strtmp,1,1,ipfile);
			fflush(ipfile);
			fclose(ipfile);
		}
/*			nvram_bufset(RT2860_NVRAM, "serverweb", WebADDR);
//			nvram_commit(RT2860_NVRAM);
		strcpy(WebADDR,"");
		nvram_bufset(RT2860_NVRAM, "serverip", WebADDR);*/
//			nvram_commit(RT2860_NVRAM);
	}else
	{			
		FILE* ipfile=fopen(SIPFILEPATH,"w");
		if(ipfile)
		{
			fseek(ipfile,0,SEEK_SET);
			fwrite(WebADDR,strlen(WebADDR),1,ipfile);
			fflush(ipfile);
			fclose(ipfile);
		}
		FILE* webfile=fopen(WebIPFile,"w");
		if(webfile)
		{
//			    strcpy(WebADDR,"\0");
			unsigned char strtmp[2]={"\0"};
			fseek(webfile,0,SEEK_SET);
//    			fwrite(WebADDR,strlen(WebADDR),1,webfile);
			fwrite(strtmp,1,1,webfile);
			fflush(webfile);
			fclose(webfile);
		}
	}
/*			nvram_bufset(RT2860_NVRAM, "serverip", WebADDR);
//			nvram_commit(RT2860_NVRAM);
		strcpy(WebADDR,"");
		nvram_bufset(RT2860_NVRAM, "serverweb", WebADDR);
//			nvram_commit(RT2860_NVRAM);
	}		
	nvram_bufset(RT2860_NVRAM, "serverport", WebPORT);	
//	    nvram_commit(RT2860_NVRAM);
	nvram_bufset(RT2860_NVRAM, "camera0ip", gate0CameraADDR);
//		nvram_commit(RT2860_NVRAM);
	nvram_bufset(RT2860_NVRAM, "camera1ip", gate1CameraADDR);
//		nvram_commit(RT2860_NVRAM);
	nvram_bufset(RT2860_NVRAM, "camera0port", gate0crPORT);
//		nvram_commit(RT2860_NVRAM);
	nvram_bufset(RT2860_NVRAM, "camera1port", gate1crPORT);
//		nvram_commit(RT2860_NVRAM);
	nvram_bufset(RT2860_NVRAM, "cmdresultpath", cmdresult);
//		nvram_commit(RT2860_NVRAM);
	nvram_bufset(RT2860_NVRAM, "realtimepath", realtime);
//		nvram_commit(RT2860_NVRAM);
	nvram_bufset(RT2860_NVRAM, "detectdevicepath", DetectDevice);
//		nvram_commit(RT2860_NVRAM);
	nvram_bufset(RT2860_NVRAM, "request_time", request_time);
	nvram_commit(RT2860_NVRAM);*/
	FILE* cripfile=fopen(Camera0IPFILE,"w");
	if(cripfile)
	{
		fseek(cripfile,0,SEEK_SET);
		fwrite(gate0CameraADDR,strlen(gate0CameraADDR),1,cripfile);
		fflush(cripfile);
		fclose(cripfile);
	}
	FILE* crportfile=fopen(Crport0FILE,"w");
	if(crportfile)
	{
		fseek(crportfile,0,SEEK_SET);
		fwrite(gate0crPORT,strlen(gate0crPORT),1,crportfile);
		fflush(crportfile);
		fclose(crportfile);
	}
//		printf("gate0crPORT w ok...%d\n",__LINE__);
	cripfile=fopen(Camera1IPFILE,"w");
	if(cripfile)
	{
		fseek(cripfile,0,SEEK_SET);
		fwrite(gate1CameraADDR,strlen(gate1CameraADDR),1,cripfile);
		fflush(cripfile);
		fclose(cripfile);
	}
	crportfile=fopen(Crport1FILE,"w");
	if(crportfile)
	{
		fseek(crportfile,0,SEEK_SET);
		fwrite(gate1crPORT,strlen(gate1crPORT),1,crportfile);
		fflush(crportfile);
		fclose(crportfile);
	}
//		printf("gate1crPORT w ok...%d\n",__LINE__);
	
	FILE* portfile=fopen(SPORTFILEPATH,"w");
	if(portfile)
	{
		fseek(portfile,0,SEEK_SET);
		fwrite(WebPORT,strlen(WebPORT),1,portfile);
		fflush(portfile);
		fclose(portfile);
	}
/*	portfile=fopen(DWTCPPORTFILEPATH,"w");
	if(portfile)
	{
		fseek(portfile,0,SEEK_SET);
		fwrite(TcpPORT,strlen(TcpPORT),1,portfile);
		fflush(portfile);
		fclose(portfile);
	}*/
	portfile=fopen(DWJQFSLJ,"w");
	if(portfile)
	{
		fseek(portfile,0,SEEK_SET);
		fwrite(jqfs,strlen(jqfs),1,portfile);
		fflush(portfile);
		fclose(portfile);
	}
//		printf("TcpPORT w ok...%d\n",__LINE__);
	
	FILE* rqtimefile=fopen(RqtimeFILEPATH,"w");
	if(rqtimefile)
	{
//		    strcpy(request_time,"15");
		fseek(rqtimefile,0,SEEK_SET);
		fwrite(request_time,strlen(request_time),1,rqtimefile);
		fflush(rqtimefile);
		fclose(rqtimefile);
	}
	printf("request_time w ok...%d\n",__LINE__);
	rqtimefile=fopen(cmdresultFile,"w");
	if(rqtimefile)
	{
//		    strcpy(request_time,"15");
		fseek(rqtimefile,0,SEEK_SET);
		fwrite(cmdresult,strlen(cmdresult),1,rqtimefile);
		fflush(rqtimefile);
		fclose(rqtimefile);
	}
	printf("cmdresult w ok...%d\n",__LINE__);
	rqtimefile=fopen(realtimeFile,"w");
	if(rqtimefile)
	{
//		    strcpy(request_time,"15");
		fseek(rqtimefile,0,SEEK_SET);
		fwrite(realtime,strlen(realtime),1,rqtimefile);
		fflush(rqtimefile);
		fclose(rqtimefile);
	}
//		printf("realtimeFile w ok...%d\n",__LINE__);
	rqtimefile=fopen(DetectDeviceFile,"w");
	if(rqtimefile)
	{
//		    strcpy(request_time,"15");
		fseek(rqtimefile,0,SEEK_SET);
		fwrite(DetectDevice,strlen(DetectDevice),1,rqtimefile);
		fflush(rqtimefile);
		fclose(rqtimefile);
	}
	printf("DetectDeviceFile w ok...%d\n",__LINE__);

	websHeader(wp);
//        websWrite(wp, T("<script language=\"javascript\">alert(\"服务器参数设置成功。系统将重启，可能需要约1分钟。\");</script><br/>"));   //don't use '' instead of ""
	websWrite(wp, T("<script language=\"javascript\">alert(\"服务器参数设置成功。\");</script><br/>"));   //don't use '' instead of ""
	websWrite(wp, T("<script language=\"javascript\">self.setTimeout(window.location.href='/door/gatesetting.asp',\
		5000);</script><br/>"));
	websFooter(wp);
	websDone(wp, 200);
//    doSystem("reboot");
//	doSystem("killall dwwiegand && dwwiegand&");
//	doSystem("killall dwwiegand || dwwiegand&");
	doSystem("killall dwwiegand");
	doSystem("dwwiegand&");
//	}	
    return;
}

static void staffinit(webs_t wp, char_t *path, char_t *query)
{
    websText(wp);
	if(!(*query) || (!strlen(query)))
	{	    
		websWrite(wp, T("%s<br/>"),"query NULL.");
		websDone(wp, 200);
		return;
	}
	char_t* strbuf;
	strbuf = balloc(B_L,96);
	strcpy(strbuf,query);
	char_t* base64de;
	base64de = balloc(B_L,96);
	websDecode64(base64de,strbuf,96);
//	printf("base64de:%s strbuf:%s %d\n",base64de,strbuf,__LINE__);
    char_t* deReturn;
	deReturn = balloc(B_L,96);
    char_t* deReturnpre;
	deReturnpre = balloc(B_L,96);	
    if(!strcmp(base64de,"{\"cmd_code\":\"dwyuangongbiaochushihua\"}"))
	{
        char_t* sqlstr;
	    sqlstr = balloc(B_L,256);
		int ncols=0,nrows=0;
		char_t* staffnumbuff;
	    staffnumbuff = balloc(B_L,33);
	    snprintf(sqlstr,255,"DELETE FROM staffbasesetting WHERE staffnum!='1';");
	    if(dwreadwriteDB(sqlstr,(unsigned char**)&staffnumbuff,&ncols,&nrows)<0)
		{
		    snprintf(deReturnpre,96,"{\"result\":\"error\"}");
	        websEncode64(deReturn,deReturnpre,96);
	        websWrite(wp, T("%s"),deReturn);
	        websDone(wp, 200);
//            printf("sqlstr:%s %d\n",sqlstr,__LINE__);			
		}else
		{
	        snprintf(deReturnpre,96,"{\"result\":\"success\"}");
			websEncode64(deReturn,deReturnpre,96);
	        websWrite(wp, T("%s"),deReturn);
	        websDone(wp, 200);
//			printf("sqlstr:%s %d\n",sqlstr,__LINE__);
	    }
		bfree(B_L,sqlstr);
		bfree(B_L,staffnumbuff);
	}else
	{
       snprintf(deReturnpre,96,"{\"result\":\"error\"}");
	   websEncode64(deReturn,deReturnpre,96);
	   websWrite(wp, T("%s"),deReturn);
	   websDone(wp, 200);
//	   printf("base64de:%s %d\n",base64de,__LINE__);
	}
	bfree(B_L,strbuf);
	bfree(B_L,base64de);
	bfree(B_L,deReturn);
	bfree(B_L,deReturnpre);
	return;
}
